Sub topic 3
Passing arguments to handlers
This chapter assumes you know JavaScript arrow functions, basic JSX, components and props, and useState. It also assumes you can already attach a handler such as onClick={handleClick}.
The problem
React calls a handler with one argument: the event object. Often a handler needs something else, such as the id of the item that was clicked. You can't write that value into the prop directly, because onClick={onSelect(item.id)} calls onSelect during render and passes its return value to onClick.
Wrap the call in an arrow function
Pass a new function that calls your handler with the values you want. The arrow function is the reference React stores. It runs only when the click happens.
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. Each of those functions closes over its own item, so every button reports its own id.
flowchart TDCall versus reference
These two lines look similar but behave differently.
| JSX | What happens |
|---|---|
| `onClick={handleClick}` | Passes the function. React calls it on click. |
| `onClick={handleClick(id)}` | Calls it during render and passes the result. |
| `onClick={() => handleClick(id)}` | Passes a new function. It calls `handleClick(id)` on click. |
If handleClick(id) sets state, the first mistake also causes an infinite render loop, because each render triggers another update.
Keeping the event as well
The arrow function receives the event, so you can forward it next to your own arguments. Put the event where your handler expects it.
import { useState } from 'react';
function Palette() {
const [last, setLast] = useState('none');
function handlePick(color, e) {
setLast(`${color} (${e.type})`);
}
return (
<div>
{['red', 'green', 'blue'].map(color => (
<button key={color} onClick={e => handlePick(color, e)}>
{color}
</button>
))}
<p>Last pick: {last}</p>
</div>
);
}Clicking "green" shows green (click). If you don't need the event, leave it out of the arrow function's parameters, as the List example does.
Alternatives to inline arrows
Inline arrows are the usual choice, and the cost of creating one per render is rarely noticeable. Two alternatives exist for cases where an inline arrow is awkward.
- Read the value from the element. Store it in a
data-attribute and read it frome.currentTarget.dataset. This keeps one shared handler, but the value is always a string. - A function that returns a handler. Write
makeHandler(id)so that it returns() => .... This is the same pattern as an inline arrow, moved into a named function.
function Tags({ tags, onRemove }) {
const makeRemover = tag => () => onRemove(tag);
return tags.map(tag => (
<button key={tag} onClick={makeRemover(tag)}>
Remove {tag}
</button>
));
}Here makeRemover(tag) runs during render, and that is intended. It returns the function that React stores.
Common errors
- Calling the handler in JSX.
onClick={onSelect(item.id)}runs at render time. Add() =>. - Using
bindor arrow wrappers for no reason.onClick={handleClick}is enough when the handler needs only the event. - Wrong argument order. If the handler is
(color, e), the call must behandlePick(color, e). React does not reorder arguments for you. - Reading
e.targetfor data. In nested markup,targetmay be a child element such as an icon. An argument from the closure is more reliable.
Exercise
A teammate writes <button onClick={deleteItem(item.id)}>Delete</button> and finds that every item is deleted as soon as the list renders. Why does this happen, and how do you fix it?
Show answer
deleteItem(item.id) is called during render, and its return value is passed to onClick. Wrap it in an arrow function: <button onClick={() => deleteItem(item.id)}>Delete</button>. React then calls the arrow function only when the click happens.