Question

What do you need to be aware of when using a method of a React component class as an event handler?

#react #javascript

Answer

The binding of this.

In the example below, if the bind() in the constructor were not used, when the handleClick method were called through onClick, the value of this within handleClick would be undefined. This is because in JavaScript, class methods are not bound by default.

There are other ways besides bind to get around this.

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isToggleOn: true };

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({ isToggleOn: !state.isToggleOn }));
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
} 

https://reactjs.org/docs/handling-events.html

Learn

Author

xavi

Reviews
Last
next

Students 1