Event Handling
Event Handling
React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on.
Adding Event Handlers
To add an event handler, you first define a function and then pass it as a prop to the appropriate JSX tag.
export default function Button() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
Notice how we pass handleClick and not handleClick().
- Correct:
<button onClick={handleClick}>(Passes the function reference. React will call it only when the user clicks). - Incorrect:
<button onClick={handleClick()}>(Calls the function immediately during render, often causing infinite loops if it sets state).
Inline Event Handlers
You can also define an event handler inline using an arrow function. This is especially useful if you need to pass an argument to your handler.
<button onClick={() => alert('You clicked me!')}>
Click me
</button>
Passing Arguments to Event Handlers
If you need to pass an argument (like an ID) to your event handler, you must wrap the call in an arrow function so it isn’t executed immediately during render.
function App() {
const deleteUser = (userId) => {
// delete user logic
};
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
{/* ✅ Correct: wrapped in an arrow function */}
<button onClick={() => deleteUser(user.id)}>Delete</button>
{/* ❌ Wrong: executes immediately on render! */}
{/* <button onClick={deleteUser(user.id)}>Delete</button> */}
</li>
))}
</ul>
);
}
Passing Event Handlers as Props
Often you’ll want the parent component to specify a child’s event handler. For example, a DesignButton component doesn’t know what it should do when clicked; only the parent using it knows. You can pass the event handler down as a prop.
function DesignButton({ onClick, children }) {
return (
<button className="fancy-btn" onClick={onClick}>
{children}
</button>
);
}
function App() {
function handlePlayClick() {
alert('Playing!');
}
return (
<DesignButton onClick={handlePlayClick}>
Play Movie
</DesignButton>
);
}
Interview Questions
Q: How do React events differ from native HTML DOM events?
A: React does not attach event listeners directly to the actual DOM nodes you render. Instead, it uses Event Delegation by attaching a single master event listener to the root of the document. When an event fires, React catches it, wraps it in a cross-browser SyntheticEvent object, and simulates the bubbling phase internally.