Sub topic 1
Attaching event handlers to elements
Prerequisites
This chapter assumes you know the following:
- JavaScript functions and arrow functions
- Basic JSX syntax
- Components and props in React
- The basics of the
useStatehook
The working model
React lets you attach a handler to an element by passing a function to an event prop. An event prop is a JSX attribute whose name starts with on and continues in camelCase, such as onClick, onChange, or onSubmit. React calls your function when the matching event happens on that element.
function SaveButton() {
function handleClick() {
alert('Saved');
}
return <button onClick={handleClick}>Save</button>;
}The handler is defined inside the component and passed as onClick={handleClick}. By convention, handler functions are named handleX, where X describes the event, such as handleClick or handleSubmit.
The flow looks like this:
Your component only hands React a function. React decides when to run it.
Pass the function, do not call it
The most common mistake is calling the function in the JSX instead of passing it.
| Code | What happens |
|---|---|
| `onClick={handleClick}` | Passes the function. React calls it on click. |
| `onClick={handleClick()}` | Calls the function during render. The result (usually `undefined`) is passed to `onClick`. |
| `onClick={() => handleClick()}` | Passes a new arrow function that calls `handleClick` on click. |
With handleClick(), the alert in the example above would fire every time the component renders, and clicking would do nothing. If you see an action happening on page load, check for stray parentheses.
Inline handlers
For short logic, you can write the function directly in the JSX:
function LogButton() {
return <button onClick={() => console.log('clicked')}>Log</button>;
}This is fine for one-liners. Once a handler grows beyond a line or two, move it into a named function so the markup stays readable.
Inline arrow functions are also the usual way to give a handler extra data. Inside a list, each button needs to report which item it belongs to:
function List({ items, onSelect }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>
<button onClick={() => onSelect(item.id)}>{item.name}</button>
</li>
))}
</ul>
);
}Each button gets its own arrow function that closes over its own item. When clicked, it calls onSelect with that item's id. Later chapters cover passing arguments and props in more detail.
Which elements and events are available
Event props are available on built-in elements such as <button>, <input>, <form>, and <div>. Examples include:
onClickfor clicksonChangefor input value changesonSubmitfor form submissiononKeyDownfor key pressesonFocusandonBlurfor focus changes
Event props on your own components are different. Writing <MyButton onClick={...} /> does not attach anything to the DOM by itself. onClick is just a prop with that name, and MyButton must pass it to an element for it to have any effect. The chapter on passing handlers between components covers this.
Common errors
- Calling the handler during render. Covered above. Remove the parentheses or wrap the call in an arrow function.
- Using lowercase or HTML names. React uses
onClick, notonclick. Likewise,onChange, notonchange. - Passing a string. In HTML you may write
onclick="save()". In JSX, the value must be a function:onClick={save}. - Expecting a custom component to handle the event. A prop named
onClickon a component does nothing unless the component uses it.
Exercise
A component renders <button onClick={handleDelete(item.id)}>Delete</button>. Items are deleted as soon as the page loads, and clicking the button does nothing. Why does this happen, and how do you fix it?
Show answer
handleDelete(item.id) is called during render, so the deletion runs immediately and its return value (probably undefined) is passed to onClick. Wrap the call in an arrow function so React calls it on click: onClick={() => handleDelete(item.id)}.