this.handleChange = this.handleChange.bind(this);

Viewed 9044

I don't understand why I need

this.handleChange = this.handleChange.bind(this);

to make my program work:

class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = { foo: 1 }
    }

    render() {
        return (
                <div>
                <input onChange={this.handleChange} value="xxx" />
                <span>yes {this.state.foo}</span>

                </div>



        );
    }

    handleChange(e) {
        console.log("called 1");
        this.setState({foo: this.state.foo+1});
    }

}


ReactDOM.render(<Foo />, document.getElementById("name1") )

In other words, what does

this.handleChange = this.handleChange.bind(this);

do in layman's terms

1 Answers

In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

If calling bind annoys you, there are two ways you can get around this. you can use the experimental public class fields syntax or arrow functions in the callback:

Arrow Function Example:

    class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}
Related