Event Handling in React
Wiring up clicks, input changes, and other DOM events with React's event props and synthetic event system.
2 min read
React handles events through props like onClick, onChange, and onSubmit, written directly on JSX elements:
function Button() {
function handleClick() {
console.log("Clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}Pass the function, don't call it
The single most common beginner mistake here is calling the function instead of passing a reference to it:
// Wrong — calls handleClick immediately during render, not on click
<button onClick={handleClick()}>Click me</button>
// Right — passes the function itself, React calls it on click
<button onClick={handleClick}>Click me</button>onClick={handleClick()} runs handleClick right away while React is rendering the component, and whatever it returns (usually undefined) becomes the onClick value — so nothing happens when you actually click.
Passing arguments
Since you can't write onClick={handleClick(id)}, wrap the call in an inline arrow function instead, which delays the call until the click actually happens:
function TodoItem({ id, onDelete }) {
return <button onClick={() => onDelete(id)}>Delete</button>;
}The event object
Handlers receive React's synthetic event object, which wraps the browser's native event with a consistent API across browsers:
function Input() {
function handleChange(e) {
console.log(e.target.value);
}
return <input onChange={handleChange} />;
}e.target is the actual DOM element the event fired on, so e.target.value is the standard way to read an input's current text as the user types.
Preventing default behavior
Form submissions and link clicks have default browser behavior — a form reloads the page on submit by default — which you'll almost always want to stop in a React app so you can handle the submission in JavaScript instead:
function Form() {
function handleSubmit(e) {
e.preventDefault();
// handle the submission yourself
}
return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}Event handler naming convention
The convention is handleX for the function and onX for the prop — handleClick/onClick, handleSubmit/onSubmit — which isn't enforced by React but is consistent enough across codebases that deviating from it makes code harder to skim.
With props, state, and events covered, the next section turns to Hooks — starting with what a Hook actually is and the rules that govern how you can use them.