Pass a function to onClick and read the event React gives it. One handler serves two buttons.
React · beginner · 6 min · 11 steps · free
import { useState } from 'react';
export default function ColorPicker() {
const [color, setColor] = useState('gray');
function handleClick(e) {
const picked = e.target.textContent;
setColor(picked);
}
return (
<div>
<p style={{ color }}>Selected: {color}</p>
<button onClick={handleClick}>red</button>
<button onClick={handleClick}>blue</button>
</div>
);
}<ColorPicker> for the first time: it calls the ColorPicker function.useState runs for the first time, so React stores the starting value for color and returns it: "gray".onClick={handleClick} passes the function itself: React will call it when a click happens.handleClick and passes it an event object, e.e.target is the element that was clicked, so picked = "blue".setColor(picked) does not change color right away: React queues the update and will render again. In this call color is still "gray".<ColorPicker> again (render 2): it calls ColorPicker once more, from the top.useState returns the value React has kept for color: "blue". The starting value is only used on the first render.ColorPicker returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: Calls handleClick during render. The () calls it immediately.
Answer: e.target
← useState: What Happens on a Click · State Is a Snapshot →