Sub topic 1
Attaching Event Handlers to Elements
Prerequisites
This chapter assumes you know JavaScript functions and arrow functions, basic JSX, React components and props, and the useState hook.
Attaching Event Handlers to Elements
A React event handler is a function that runs after a user action, such as a click or key press. Pass the function to an event prop such as onClick. Pass the function reference, without calling it during rendering.
function SaveButton() {
function handleClick() {
alert('Saved');
}
return <button onClick={handleClick}>Save</button>;
}onClick={handleClick} tells React which function to call later. onClick={handleClick()} calls the function while React renders, which is usually a mistake.
React uses camelCase event names, including onClick, onChange, and onSubmit.
Reading the Event Object
React passes an event object to the handler. The object contains information about the action and the element involved.
function SearchBox() {
function handleChange(event) {
console.log(event.target.value);
}
function handleKeyDown(event) {
if (event.key === 'Enter') {
console.log('Search');
}
}
return (
<>
<input onChange={handleChange} onKeyDown={handleKeyDown} />
</>
);
}Here, event.target is the input element, and event.target.value is its current text. event.key identifies the key that was pressed.
Passing Arguments to Handlers
Use an inline arrow function when the handler needs additional data. The arrow function receives the event automatically if you include it.
function List({ items, onSelect }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>
<button onClick={() => onSelect(item.id)}>
{item.name}
</button>
</li>
))}
</ul>
);
}The arrow function delays the call until the click. It passes the selected item's ID to onSelect.
Passing Handlers Between Components
A parent can pass a handler as a prop. Use onX names for handler props and handleX names for functions.
flowchart TD
Parent["Parent defines handleSelect"] --> Child["Child receives onSelect"]
Child --> Action["Child calls onSelect(item.id)"]
Action --> ParentThis keeps the decision in the parent while the child reports what happened.
Exercise
Why does a button use onClick={() => onSelect(id)} instead of onClick={onSelect(id)}?
Show answer
The arrow function delays the call and supplies id when the click occurs. The second form calls onSelect during rendering.