Handling Events in React
Handling Events in React
React events look like HTML events but follow JSX conventions. Handlers are passed as props, and they receive a synthetic event object that wraps the browser event.
Attaching a handler
function Button() {
function handleClick() {
console.log('Pressed');
}
return <button onClick={handleClick}>Press me</button>;
}
Note the differences from HTML: the event name is camelCase, onClick, and the value is a JavaScript reference, not a string.
Inline handlers and arguments
You can pass arguments to a handler using an arrow function:
<button onClick={() => save(id)}>Save</button>
The arrow runs when the click happens and calls save with the id. This is the common way to handle events that need extra data.
The event object
function Field() {
function handleChange(event) {
console.log(event.target.value);
}
return <input onChange={handleChange} />;
}
The synthetic event behaves like a native event. Use event.target.value to read input values and preventDefault on forms to stop page reloads:
<form onSubmit={(e) => { e.preventDefault(); submit(); }}>
Form handling with controlled inputs
Combine events with state to make controlled inputs, where the input value mirrors state:
const [text, setText] = useState('');
<input value={text} onChange={(e) => setText(e.target.value)} />
Best practices
Define named handler functions for anything nontrivial. Pull logic into separate functions so components stay readable. Avoid heavy work inside handlers; keep them short and delegate.
Key Points
- Event properties are camelCase, like onClick.
- Handlers are function references, not strings.
- Arrow functions pass extra arguments or stop default behavior.
- event.target exposes form values.
- Controlled inputs tie state to form fields.