How to handle events in React components
· Category: React
Short answer
React wraps native DOM events in a SyntheticEvent system for cross-browser consistency. You attach handlers with camelCase props like onClick and pass functions, not strings.
Steps
- Define an event handler function.
- Attach it to a JSX element using
onEventName. - If you need to pass extra arguments, use an arrow function or bind in the render.
- Call
event.preventDefault()to stop default browser behavior when needed.
Example
function Form() {
const handleSubmit = (event) => {
event.preventDefault();
console.log('Submitted');
};
const handleClick = (id) => {
console.log('Clicked item', id);
};
return (
<form onSubmit={handleSubmit}>
<button type="button" onClick={() => handleClick(42)}>
Click me
</button>
</form>
);
}
Tips
- Avoid defining arrow functions directly in render for heavy lists; it creates a new function on every render.
- The SyntheticEvent is pooled in older React versions; for async access, call
event.persist(). This is unnecessary in React 17+.