Counter
Build a simple counter with increment, decrement, and reset buttons, displaying the live count in an accessible status region. The count may go negative.
Create a Counter component that manages a single number, starting at 0.
Render three buttons and a live count display:
- A "+" button that increases the count by 1.
- A "-" button that decreases the count by 1 (the count is allowed to go below zero).
- A "Reset" button that sets the count back to
0.
The current count must be shown in an element with role="status" so assistive technology announces updates. The text should read exactly like the number (for example 0, then 3, then -2).
This is a fundamental React state exercise: hold the value in useState, and wire each button's onClick to update it. Because the "+" and "-" labels are symbol-only, give each button an explicit aria-label ("increment" / "decrement") so it is accessible and easy to target in tests.
Requirements
- Maintain a numeric count in component state, initialized to 0.
- Render a '+' button (aria-label "increment") that increases the count by 1 on click.
- Render a '-' button (aria-label "decrement") that decreases the count by 1 on click; the count may become negative.
- Render a 'Reset' button that sets the count back to 0.
- Display the current count inside an element with role="status" whose text content is the number itself.
Hints (4)
- Use const [count, setCount] = useState(0) to hold the value.
- Update with the functional form: setCount(c => c + 1) and setCount(c => c - 1); Reset uses setCount(0).
- Symbol-only buttons ('+' and '-') need an aria-label so they are accessible — give them aria-label="increment" and aria-label="decrement".
- Put the count in a <p role="status"> (or any element with role="status") so screen readers and tests can read the live value.
Topics
- React
- React Components
Asked at
Razorpay · Ola · Delhivery · Freshworks · Flipkart · Zerodha
