A handler is a function React calls when something happens, like a click. Instead of writing an arrow function inside onClick, you can declare the function above return, give it a name, and hand that name to the button. Declared inside the component, it can read the component's state.
Here is a like button in another component:
function like() {
setLikes(likes + 1);
}
return <button onClick={like} disabled={likes === 10}>Like</button>;
Write onClick={like}, the name without parentheses: React keeps the function and calls it on each click. onClick={like()} calls it right away, while React draws. It sets state, which starts a new draw, which calls it again, and React stops with the error Too many re-renders.
disabled takes true or false. A disabled button can't be clicked, so the likes above stop at 10.
The check clicks in the Mug and must see:
> open the page Mug: Quantity: 1, button: - (disabled), button: + > click "+" in "Mug" Quantity: 1 → 2, and - is no longer disabled > click "+" in "Mug" Quantity: 2 → 3 > click "-" in "Mug" Quantity: 3 → 2 > click "-" in "Mug" Quantity: 2 → 1, and - is disabled again > click "-" in "Mug" (it is disabled: nothing happens)
Your task: in src/QuantityPicker.jsx, write the handlers increase and decrease, a + button that calls increase, and a - button above it that calls decrease and is disabled when the quantity is 1.
Assignment
Follow the Coding Tutorial to turn the picker's click code into named handlers and add a - button that stops at 1.
Hint
Hand the button the handler's name, onClick={increase}, without parentheses. For the - button, disabled gets a comparison that is true when the quantity is 1.
Free plan: 30 tutor messages. PRO is unlimited.
