Handling Events

Pass a function to onClick and read the event React gives it. One handler serves two buttons.

React · beginner · 6 min · 11 steps · free

What you'll learn

Events.jsx

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>
  );
}

Step by step

  1. React renders <ColorPicker> for the first time: it calls the ColorPicker function.
  2. useState runs for the first time, so React stores the starting value for color and returns it: "gray".
  3. Both buttons get the same handler. onClick={handleClick} passes the function itself: React will call it when a click happens.
  4. React turns the JSX into real page elements and shows them: look at the Screen panel.
  5. You click "blue". React calls handleClick and passes it an event object, e.
  6. e.target is the element that was clicked, so picked = "blue".
  7. setColor(picked) does not change color right away: React queues the update and will render again. In this call color is still "gray".
  8. React renders <ColorPicker> again (render 2): it calls ColorPicker once more, from the top.
  9. useState returns the value React has kept for color: "blue". The starting value is only used on the first render.
  10. ColorPicker returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  11. The paragraph now says blue, in blue.

Common mistakes

Best practices

Key takeaways

Check yourself

onClick={handleClick()} does what?

Answer: Calls handleClick during render. The () calls it immediately.

Which gives the clicked element?

Answer: e.target

·

More in State and Events