Number and buttons
- React course
- Beginner
- Lesson 46/84
- 5 min
Add the number display and the increment button.
Decrement and reset
To decrease the counter call setCount(count - 1); to reset call setCount(0). Each gets its own handler and button.
You place two buttons side by side: one "−1", one "Reset". Each button calls its own handler.
This pattern shows how one component manages several interactions.
Two buttons side by side
You return the decrement and reset buttons together as sibling JSX in one return. React wants a single root; you wrap two siblings in a <div> or a <> fragment.
A fragment <>...</> groups without adding a DOM node; we cover it in detail later.
Each button gets its own onClick; handlers live in the component.
Practice Decrement and reset
Complete the skeleton. Write a Counter component; import useState. Define const [count, setCount] = useState(0);. In handleDown call setCount(count - 1); in handleReset call setCount(0). Return two buttons in a <>: <button onClick={handleDown}>-</button> and <button onClick={handleReset}>Reset</button>. Export it.
Starter code
import { useState } from "react";
// Define Counter hereSample solution
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleDown() { setCount(count - 1); }
function handleReset() { setCount(0); }
return <><button onClick={handleDown}>-</button><button onClick={handleReset}>Reset</button></>;
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which call resets?
The updater can be called with a constant.- setCount(0) Correct answer
- setCount(count)
- count = 0
- reset()
Explanation: setCount(0) brings the number back to start.
2 Number and buttons: fill in the missing part
function handleDown() { setCount(____); }
function handleDown() { setCount(count - 1); }
Explanation: You subtracted one from the current value.
3 Number and buttons: match the terms
| Term | Meaning |
|---|---|
handleDown |
Decrement |
handleReset |
Reset |
setCount(0) |
Zero |
<>...</> |
Fragment |