How to Handle Events in React: Simple Guide with Examples
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.
import React from 'react'; function Button() { function handleClick() { alert('Clicked!'); } return <button onClick={handleClick}>Click me</button>; } export default Button;
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.
import React from 'react'; function Button() { function handleClick() { alert('Clicked!'); } return <button onClick={handleClick}>Click me</button>; } export default Button;
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.
import React from 'react'; function Button({ message }) { return <button onClick={() => alert(message)}>Click me</button>; } export default Button;
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.