0
0
ReactDebug / FixBeginner · 4 min read

How to Handle Events in React: Simple Guide with Examples

In React, you handle events by passing a function to an event attribute like onClick on an element. Use a function or arrow function to define the event handler, and React will call it when the event happens.
🔍

Why This Happens

Sometimes beginners try to call the event handler function directly instead of passing it as a reference. This causes the function to run immediately during rendering, not when the event happens.

jsx
import React from 'react';

function Button() {
  function handleClick() {
    alert('Clicked!');
  }

  return <button onClick={handleClick}>Click me</button>;
}

export default Button;
Output
Error or unexpected behavior: The alert shows immediately when the page loads, not when the button is clicked.
🔧

The Fix

Pass the event handler function without calling it by removing the parentheses. This way, React knows to call it only when the event happens.

jsx
import React from 'react';

function Button() {
  function handleClick() {
    alert('Clicked!');
  }

  return <button onClick={handleClick}>Click me</button>;
}

export default Button;
Output
When you click the button, an alert saying 'Clicked!' appears.
🛡️

Prevention

Always pass a function reference to event handlers, not the result of calling a function. Use arrow functions if you need to pass arguments. Enable linting rules like react/jsx-no-bind to catch common mistakes early.

jsx
import React from 'react';

function Button({ message }) {
  return <button onClick={() => alert(message)}>Click me</button>;
}

export default Button;
Output
Clicking the button shows an alert with the passed message.
⚠️

Related Errors

Common related errors include forgetting to bind this in class components (legacy) or using incorrect event names like onclick instead of onClick. Always use camelCase event names and functional components with hooks for modern React.

Key Takeaways

Pass event handler functions without parentheses to avoid immediate execution.
Use arrow functions to pass arguments to event handlers safely.
Always use camelCase event names like onClick in React JSX.
Prefer functional components and hooks for modern event handling.
Enable React linting rules to catch event handler mistakes early.