Sikau

React · Day 7 · about 25 min

Handling events

Respond to clicks, typing and more.

Make it respond

So far our components only display things. Now they'll *respond*. In React you don't call addEventListener — you pass an event handler straight to the element.

onClick and friends

export default function Buttons() {
  function handleOrder() {
    console.log("Order placed!");
  }

  function handleKey(e) {
    console.log("You typed:", e.target.value);
  }

  return (
    <div>
      <button onClick={handleOrder}>Order</button>
      <button onClick={() => console.log("Help is coming")}>Call waiter</button>
      <input onChange={handleKey} placeholder="Type here" />
    </div>
  );
}
  • e.preventDefault() stops a form from reloading the page (more on forms soon).
  • Child components can accept handlers as props: <Button onPress={…} /> — the parent decides what happens.

The rest of this lesson

  • The event objectexplain
  • Passing arguments safelyexplain
  • When does it log?predict
  • Event propsmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React