Responding to user events is a crucial part of building interactive UIs. In React, you can pass event handlers as props to components to run code when events occur.
Let’s look at how to listen and react to common events in React:
Binding to Events
Pass an event handler function to a component to subscribe to events:
function Button({ onClick }) {
return (
<button onClick={onClick}>
Click Me
</button>
);
}
function App() {
const handleClick = () => {
console.log('Clicked!');
};
return (
<Button onClick={handleClick} />
);
}
When the button is clicked, handleClick
will be called.
Event Object
Inside an event handler, you can access the native browser event via event
:
const handleChange = (event) => {
console.log(event.target.value);
}
<input onChange={handleChange} />
event
contains properties like target to reference the DOM element.
Supported Events
You can listen to common events like:
onClick
onSubmit
onChange
onKeyDown
onScroll
And many more. Refer to React’s SyntheticEvent docs for the full list.
Event Handler Scope
Make sure handlers are properly scoped to access component props and state:
// Won't work!
function App() {
const [text, setText] = useState('');
return (
<input
onChange={(e) => setText(e.target.value)} // no text
/>
);
}
// Bind handler instead
function App() {
const [text, setText] = useState('');
const updateText = (e) => setText(e.target.value);
return (
<input
onChange={updateText}
/>
);
}
Summary
- Pass event handlers as props to listen for events
- Access the browser event object via
event
- Use common events like
onClick
andonChange
- Bind component methods to avoid scoping issues
Mastering events allows building highly interactive React interfaces.