React Mastery / React Basics

Binding Event Handlers

πŸ”— What is Binding Event Handlers in React?

In React class components, when you create a function like an event handler (handleClick), you often need to bind that function to the component.

Binding connects the function to the component so that the keyword this inside the function refers to the component instance.


βš™οΈ Why is Binding Important in React?

In JavaScript, the value of this depends on how a function is called.

In React class components, if you pass a function like this:

<button onClick={this.handleClick}>Click Me</button>

...React will not automatically bind this.handleClick to the component.

So inside the handleClick() method, this could be undefined β€” meaning this.state or this.setState() will not work and cause an error. So this.state or this.setState() inside handleClick() throws an error, because this is not the component anymore.


πŸ›‘ When you click the button, it doesn’t do the increment. But Now, when you click the button, it correctly increments the count.