Summary

In this lesson, you learned that:

  • A handler goes right into the JSX, onClick={handleClick}, and the function is written inside the component. The names of events start with on and are in camelCase: onClick, onChange.
  • onClick gets a function, not its call. onClick={handleClick()} calls the function while the component renders, and clicks then do nothing.
  • To pass an argument, wrap the call in an arrow function: onClick={() => handleVote(band.name)}.
  • A handler with a parameter gets the event object. event.target is the element where the event happened. A text field's onChange comes after every change of its text, and event.target.value is the text.
  • A function can be a prop: <BandCard onVote={handleVote} />, and the child calls it: onVote(band.name). By convention, props for handlers are called onSomething, and handler functions handleSomething.
  • Changing a variable in a handler doesn't change the page. React doesn't know about it, and each render runs the component's function from the top again.

In the next lesson, State, you'll give components a memory: values that React keeps between renders, and that update the page when they change.

But first, a little practice: the festival's merch stand, with a cart that, for now, only prints.

Instructions

A click on Add to cart prints In the cart: Cap, €15, with the name and price of its product. Write the handler handleAdd(product) in App, pass it to each Product as the prop onAdd, and make Product call it with its product.

As someone types a discount code, print it in capital letters: Code: SUMMER. Give the field an onChange handler, and use toUpperCase().

Start programming for free

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

Or sign up with:

Back

7/7

Next