Handling Events
React event handlers look a lot like plain HTML onclick attributes, with one crucial difference: you pass a function, not a string of code to run, and not the result of calling that function.
Passing a function reference
JSX AlertButton.jsx
function AlertButton() {
function handleClick() {
alert("Button was clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}
Rendered output
A button reading "Click me". Clicking it shows a browser alert: "Button was clicked!"
onClick={"{handleClick}"} passes the function itself — React calls it for you when the click happens. Writing onClick={"{handleClick()}"} instead would call handleClick immediately while rendering, not when clicked, which is almost never what you want.
Passing arguments to a handler
To pass an argument, wrap the call in an arrow function so it still isn't executed until the click actually happens:
JSX ItemList.jsx
function ItemList() {
function handleRemove(id) {
console.log("Removing item", id);
}
return (
<ul>
<li>
Milk
<button onClick={() => handleRemove(1)}>Remove</button>
</li>
</ul>
);
}
Rendered output
A list item "Milk" with a "Remove" button. Clicking it logs: Removing item 1
The event object
React passes a synthetic event object into your handler automatically — a cross-browser wrapper around the native browser event, with the same familiar properties like .target:
JSX SearchBox.jsx
function SearchBox() {
function handleChange(event) {
console.log("You typed:", event.target.value);
}
return <input onChange={handleChange} />;
}
Rendered output
A text input. Typing "hi" logs: You typed: h You typed: hi
Note: the classic mistake is writing
onClick={"{handleClick()}"} with the parentheses — that calls handleClick the instant the component renders, not when someone clicks. If your handler seems to fire immediately and the click itself does nothing, check for a stray pair of parentheses first.