Chapter 1 of 4
Handling Events
Attaching handlers, the synthetic event object, and passing arguments.
React event props are camelCased and take a function, not a string. React attaches a single listener at the root of your app and dispatches events to your handlers itself.
// HTML
<button onclick="handleClick()">Save</button>
// React
<button onClick={handleClick}>Save</button>Passing arguments
When a handler needs an argument, wrap it in an arrow function so the call happens at click time rather than at render time.
function ItemList({ items, onDelete }) {
return items.map((item) => (
<li key={item.id}>
{item.name}
<button onClick={() => onDelete(item.id)}>Delete</button>
</li>
));
}The event object
Handlers receive a synthetic event: a cross-browser wrapper with the same API as the native event. event.target is the element that fired it, and the native event is available as event.nativeEvent.
function SearchBox() {
function handleChange(event) {
console.log(event.target.value);
}
function handleKeyDown(event) {
if (event.key === "Escape") {
event.target.blur();
}
}
return <input onChange={handleChange} onKeyDown={handleKeyDown} />;
}Preventing default behaviour
Call event.preventDefault() to stop a form submitting or a link navigating. Returning false from a React handler does nothing.
function LoginForm({ onSubmit }) {
function handleSubmit(event) {
event.preventDefault(); // stop the page reloading
onSubmit();
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Sign in</button>
</form>
);
}Bubbling and stopping it
React events bubble up the component tree just like DOM events. event.stopPropagation() prevents a parent handler from also firing.
<div onClick={selectRow}>
<button
onClick={(event) => {
event.stopPropagation(); // do not also select the row
deleteRow();
}}
>
Delete
</button>
</div>