Handling Clicks

In the JavaScript course, a button did something in three steps: you found it with querySelector(), wrote a function, and gave the function to addEventListener(). In React, you don't look for elements on the page. You write the handler right into the JSX, as an attribute of the button:

export default function App() {
    function handleHello() {
        console.log("Hello from the festival!");
    }

    return <button onClick={handleHello}>Say hello</button>;
}

Each click on the button prints a line in the console:

Hello from the festival!

What's new here:

  • onClick is on and the name of the event, in camelCase, as className is. React has such an attribute for every event you know: onClick, onChange, onSubmit, onKeyDown and others.
  • Its value is in curly braces, because it's JavaScript: the function handleHello. React keeps it and calls it on every click, as addEventListener() did.
  • The function is inside the component, right next to the JSX it belongs to. That's where handlers live in React. They can use everything the component has: its variables, its props, and soon its state.

A function that handles an event is a handler, as in the JavaScript course. In React apps, its name usually starts with handle and says what it handles: handleClick, handleBuy, handleVote. It's only a convention, React doesn't care about names, but it shows at a glance which functions are handlers.

Typical mistakes:

  • Parentheses after the name: onClick={handleHello()}. That doesn't give React the function. It calls the function right away, while the component renders. The quiz after this exercise is about it.
  • onclick in small letters, as in HTML. React doesn't know it, so clicks do nothing, and a warning in the console says what's wrong.

Instructions

In App, write a function handleBuy that prints Tickets are on sale!, and make it the click handler of the button Buy tickets. Click the button and look at the console.

Write a function handleStages for the button Show stages. It prints the stages from the array stages, joined with commas: Stages: Main Stage, Tent, Forest Stage. (join() from the JavaScript course does that.)

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

1/7

Next