Event Handling
React uses synthetic events that wrap the browser’s native events, providing consistent cross-browser behavior.
onClick
function Button() {
function handleClick() {
alert("Clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}
Pass a function reference, don’t call it: onClick={handleClick}, not onClick={handleClick()}.
onChange
function Input() {
const [value, setValue] = useState("");
return (
<input
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}
The event object e gives you access to the input’s current value.
The Event Object
React events are synthetic events — thin wrappers around native events:
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log(e.target.value);
}
return <form onSubmit={handleSubmit}>...</form>;
}
They have the same interface as native events but work identically across browsers.
Preventing Default
Use e.preventDefault() to stop default browser behavior:
function Link({ href, children }) {
function handleClick(e) {
e.preventDefault();
console.log("Navigation blocked");
}
return <a href={href} onClick={handleClick}>{children}</a>;
}
Without it, clicking a link navigates away from the page.
Passing Arguments
Use an arrow function to pass custom arguments:
function TodoList({ items }) {
function handleDelete(id) {
console.log("Delete", id);
}
return items.map(item => (
<li key={item.id} onClick={() => handleDelete(item.id)}>
{item.text}
</li>
));
}
Without the arrow function, handleDelete(item.id) runs on render, not on click.
Common Event Handlers
| Event | Handler |
|---|---|
| Click | onClick |
| Input change | onChange |
| Form submit | onSubmit |
| Key press | onKeyDown, onKeyUp |
| Mouse enter | onMouseEnter |
| Focus | onFocus, onBlur |
Best Practices
- Use descriptive names —
handleClick,handleSubmit, notonClick - Define handlers inside or outside component — Both work
- Use arrow functions for arguments —
() => handleDelete(id) - Prevent default early — First line in form handlers
Common Mistakes
- Calling the function in JSX —
onClick={handleClick()}runs immediately - Forgetting preventDefault — Forms submit and reload the page
- Using
thisin function components — There is nothiscontext - Not destructuring the event —
e.target.valuerequires the event param