Value of this in React event handler

This is correct behavior for JavaScript and React if you use the new class syntax.

The autobinding feature does not apply to ES6 classes in v0.13.0.

So you’ll need to use:

 <button onClick={this.handleClick.bind(this)}>Click</button>

Or one of the other tricks:

export default class Observer extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    /* ... */
  }
  render() {
      return <button onClick={this.handleClick}>Click</button>
  }
}

Leave a Comment