Attaching Event Handlers
React event handlers are passed as camelCase props like onClick, and receive a function reference — not a string, and not a function call.
A Basic Click Handler
function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}Passing a Function Reference, Not Calling It
onClick={handleClick} passes the function itself, to be called later by React. onClick={handleClick()} calls it immediately during render instead — a very common beginner mistake.
Passing Arguments with an Inline Arrow Function
function ItemList({ items, onRemove }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name}
<button onClick={() => onRemove(item.id)}>Remove</button>
</li>
))}
</ul>
);
}The Event Object
React passes a synthetic event object to handlers, normalized to behave consistently across browsers, with the same familiar properties and methods as a native DOM event.
Reading the Event Object
function SearchInput() {
function handleChange(event) {
console.log(event.target.value);
}
return <input onChange={handleChange} placeholder="Search..." />;
}Common Event Props
| Prop | Fires When |
|---|---|
| onClick | An element is clicked |
| onChange | A form input’s value changes |
| onSubmit | A form is submitted |
| onKeyDown | A key is pressed down |
| onMouseEnter / onMouseLeave | The pointer enters/leaves an element |
| onFocus / onBlur | An element gains or loses focus |
Preventing Default Behavior
Just like native DOM events, event.preventDefault() stops a browser’s default action — most commonly used to stop a form submission from reloading the page.
preventDefault in a Form
function SearchForm() {
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted without a page reload");
}
return (
<form onSubmit={handleSubmit}>
<input type="text" />
<button type="submit">Search</button>
</form>
);
}Best Practice
Name event handler functions starting with "handle" (handleClick, handleSubmit) — it’s a widely followed convention that makes event-driven code easy to scan at a glance.