React Events
React events let your components respond to user actions such as clicks, typing, hovering and submitting forms. You attach an event handler by passing a function to a camelCase prop like onClick or onChange.
Handling a Click
Define a function inside your component and pass it to onClick. Pass the function itself, without calling it.
function LikeButton() {
function handleClick() {
alert('Thanks for the like!');
}
return <button onClick={handleClick}>Like</button>;
}(clicking the button shows an alert: "Thanks for the like!")
A very common mistake is writing onClick={handleClick()}. The parentheses call the function immediately during rendering instead of when the user clicks.
Passing Arguments to Event Handlers
To pass a value, wrap the call in an arrow function. The arrow function is created now but only runs on click.
function Colors() {
const pick = (color) => console.log('You picked', color);
return (
<>
<button onClick={() => pick('red')}>Red</button>
<button onClick={() => pick('blue')}>Blue</button>
</>
);
}(click Blue) You picked blue
The Event Object
React passes an event object to your handler. It wraps the browser event so it behaves the same in every browser. You can read the target element, the key pressed, and more.
function SearchBox() {
function handleKeyDown(e) {
if (e.key === 'Enter') {
console.log('Searching for:', e.target.value);
}
}
return <input placeholder="Search..." onKeyDown={handleKeyDown} />;
}(type "react hooks" and press Enter) Searching for: react hooks
Preventing Default Behavior
Submitting a form normally reloads the page. Call e.preventDefault() to stop that and handle the data in JavaScript instead.
function Newsletter() {
function handleSubmit(e) {
e.preventDefault();
console.log('Subscribed!');
}
return (
<form onSubmit={handleSubmit}>
<input type="email" required />
<button type="submit">Subscribe</button>
</form>
);
}Subscribed! (page does not reload)
Common React Events
- onClick, onDoubleClick — mouse clicks
- onChange, onInput — form field values change
- onSubmit — a form is submitted
- onKeyDown, onKeyUp — keyboard keys
- onFocus, onBlur — an element gains or loses focus
- onMouseEnter, onMouseLeave — hovering
Frequently asked questions
Why does my onClick run when the page loads?
You probably wrote onClick={handleClick()} with parentheses, which calls the function during render. Pass the function itself, onClick={handleClick}, or wrap it: onClick={() => handleClick(id)}.
How do I pass a parameter to an onClick handler in React?
Use an arrow function: onClick={() => remove(item.id)}. The arrow function runs on click and calls your handler with the argument.
What is a synthetic event in React?
It is React's cross-browser wrapper around the native browser event. It has the same interface, such as target and preventDefault, and the original is available as e.nativeEvent.