Site icon Amelt.net

React.js Error “this.setState is not a function”

Amelt

Amelt

This post is also available in: 日本語 (Japanese)

In this article, I made a note when I tried to change text box value by state of React.js
By the way, the sample code of this article is used Material UI.

Uncaught TypeError: this.setState is not a function

As in the example below, if you want to change the state text value changed by "onChangeText(e)" function, you need to write "bind(this)" like the 5th line of code below.
Bind "this" by using the javascript "bind function".
If you don't write "bind(this)" in constructor, "this" object does not specified in return statement context.
In particular, React.js often needed "bind(this)".

export class Addkeyword extends React.Component {

    constructor(props) {
        super(props);
        this.state = {value: null};

        this.onChangeText = this.onChangeText.bind(this);
    }


    onChangeText(e) {
        this.setState({value: e.target.value});
    }

    render() {
        return (
             <div>
             <TextField hintText="Message Field"
             floatingLabelText="MultiLine and FloatingLabel"
             value={this.state.value}
             onChange={this.onChangeText}
             multiLine={true}
             rows={2} />

            </div>
    );
  }
}
No tags for this post.