July 30, 2021

🔗 Event Binding in React – Easy Guide for Beginners

In React, we often want to do something when the user clicks a button, types in a box, or submits a form. This is called event binding. In this blog, you’ll learn what it is and how to use it — with simple examples.


🧠 What is Event Binding?

Event binding means:

“When something happens on the webpage (like a click), run a function.”

You write this using code like onClick={handleClick}. This tells React:
“When the button is clicked, run the handleClick function.”


🛠 Function Component Example

Function components are the most common way to write React code.

Let’s make a button that counts clicks:

import React, { useState } from 'react';

function MyButton() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return <button onClick={handleClick}>Clicked {count} times</button>;
}

🔍 What’s Happening:

  • useState(0) creates a number called count, starting at 0.
  • handleClick adds 1 to count.
  • onClick={handleClick} tells React to run the function when the button is clicked.

🧱 Class Component Example

You can also use class components (older style). There are two ways to bind events here.

✅ Method 1: Use Arrow Function

This is the easy way:

class MyButton extends React.Component {
  state = { count: 0 };

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return <button onClick={this.handleClick}>Clicked {this.state.count} times</button>;
  }
}

🔁 Method 2: Use bind() in Constructor

class MyButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this); // bind the function to "this"
  }

  handleClick() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return <button onClick={this.handleClick}>Clicked {this.state.count} times</button>;
  }
}


⚠️ Common Mistake to Avoid

Don’t use () when you pass the function to the event — that runs the function immediately, not when clicked.

❌ Wrong✅ Right
onClick={handleClick()}onClick={handleClick}

✅ Summary

  • Use onClick, onChange, etc. to bind events.
  • In function components, define a function and pass it like onClick={handleClick}.
  • In class components, use arrow functions or bind() in constructor.
  • Don’t call the function directly when passing it to the event.

React makes event binding easy — once you understand the basics, you can create interactive apps fast.

Happy coding! 🚀