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 withonand are in camelCase:onClick,onChange. onClickgets 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.targetis the element where the event happened. A text field'sonChangecomes after every change of its text, andevent.target.valueis 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 calledonSomething, and handler functionshandleSomething. - 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().