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

Published on:
Last updated:

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.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.