santoku
santoku

Reputation: 3427

why material-UI textField returns 'Invalid hook call' error

I'm trying to create a textfield from Material-UI that update state in a class component. Something is wrong and it returns 'invalid hook call' error. Must Material-UI be always used with React Hooks or could it be used without?

import React, { Component } from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      year: null,
      otherAttributes: null
    };
    this.handleChangefor = this.handleChangefor.bind(this);
  }

  handleChangefor = (propertyName) => (event) => {
    this.setState({
      ...this.state,
      [propertyName]: event.target.value
    })
  }

  render() {
    return (
      <div>
        <TextField
          id="outlined-name"
          label="year"
          value={this.state.year}
          onChange={this.handleChangefor('year')}
          margin="normal"
          variant="outlined"
          />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The code can also be found here in online editor. Thanks.

Upvotes: 0

Views: 816

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

First, update your react version from 16.8.0 to 16.8.6.

Then, TextField value property can't be null, change your initial state to:

this.state = {
  year: "",
  otherAttributes: null
};

Except that your code works fine.

Edit Q-56924813-TextField

Upvotes: 1

Related Questions