Question

What are some ways to get around the undefined "this" binding in React event handlers?

#react

Answer

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
  
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

OPTION 1
Use bind() in the constructor

this.handleClick = this.handleClick.bind(this);

OPTION 2
Use the public class fields syntax

handleClick = () => {
  console.log('this is:', this);
}

OPTION 3
Use an arrow function in the callback, but notice that this is not efficient because a different callback will be created on each render

<button onClick={(e) => this.handleClick(e)}>

[^1]: https://reactjs.org/docs/handling-events.html

Learn

Author

xavi

Reviews
Last
next

Students 1