Handling Click Events
Overview
Static UIs are boring. Users need to click buttons, submit forms, and interact with the page. React provides a robust event handling system that mimics standard HTML events, but uses camelCase (e.g., onClick instead of onclick). Under the hood, React uses a 'Synthetic Event' wrapper to ensure events behave identically across all browsers (Chrome, Safari, Firefox).
Syntax
Notice that we pass `handleClick`, NOT `handleClick()`. If you add the parentheses, the function will run instantly as soon as the component renders, which is almost never what you want.
function InteractiveButton() {
// Define the event handler function
const handleClick = () => {
alert("Button was clicked!");
};
return (
// Pass the function reference (do NOT call it with ())
<button onClick={handleClick}>
Click Me
</button>
);
}If your handler needs an argument, you must wrap it in an inline arrow function: `() => myFunction(arg)`. Otherwise, adding the `(42)` would execute it on render.
function ProductList() {
const handlePurchase = (productId) => {
console.log("Bought product with ID:", productId);
};
return (
// Wrap the call in an inline arrow function to pass arguments
<button onClick={() => handlePurchase(42)}>
Buy Now
</button>
);
}Common Pitfalls
- Calling the function instead of passing it: `onClick={myFunc()}` instead of `onClick={myFunc}`.
- Losing `this` context in class components (not an issue in modern functional components with arrow functions).
Interview Tips
- Interviewers might ask about 'Synthetic Events'. Explain that React doesn't attach an event listener to every single button. It attaches one global listener to the root (Event Delegation) and routes the events synthetically for huge performance gains.
Real-World Example
Preventing default form submission behavior is a common event handling task.
function SearchForm() {
const handleSubmit = (event) => {
// Prevents the browser from refreshing the page
event.preventDefault();
console.log("Searching...");
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Search..." />
<button type="submit">Go</button>
</form>
);
}