Handlers with Arguments

Often one handler serves many buttons, and each button has to tell it something different: which band you vote for, which day you want to see. So the handler has a parameter:

function handleVote(name) {
    console.log(`Your vote: ${name}`);
}

But how do you give it the argument? onClick={handleVote("Owl Choir")} is a call, the mistake from the quiz: it would print at once, while rendering, and never on a click. Instead, wrap the call in an arrow function:

<button onClick={() => handleVote("Owl Choir")}>Vote</button>

() => handleVote("Owl Choir") is a new function without parameters. That's what React gets and calls on the click, and only then does it call handleVote() with the argument. You'll write handlers with arguments like this all the time, in lists too:

{bands.map((band) => (
    <li key={band.id}>
        {band.name}
        <button onClick={() => handleVote(band.name)}>Vote</button>
    </li>
))}

Each button gets its own arrow function, with its own band: the button of Lunar Cats calls handleVote("Lunar Cats"), and the button of Owl Choir calls handleVote("Owl Choir"). You can pass anything this way: an id, a text, or the whole object, as in handleInfo(band).

When a handler needs no argument, it needs no arrow function either: onClick={handleBuy} is enough. The arrow function is only there to pass the argument.

Instructions

Write a function handleVote(name) that prints Your vote: Owl Choir, with the name it gets. Give each Vote button a handler that calls it with the name of its band.

Write a function handleDay(day) that prints the names of the bands that play on that day, joined with commas, such as Night Trains, Lunar Cats for Friday. The buttons Friday and Saturday call it with their day. (filter(), map() and join() will do it.)

Start programming for free

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

Or sign up with:

Back

3/7

Next