Like Button
Build a toggle Like button that flips between "Like" and "Liked", reflects its state via aria-pressed, and shows a live like count.
Create a LikeButton (rendered by App) that lets a user toggle whether they like an item.
The component renders a single real <button>:
- When not liked, the button text reads
Likeand itsaria-pressedattribute is"false". - When liked, the button text reads
Likedand itsaria-pressedattribute is"true".
Clicking the button toggles between these two states.
Separately, render an element with role="status" that displays the like count:
- The count starts at
0. - When the button becomes liked, the count is
1. - When the button is toggled back to unliked, the count returns to
0.
The status text should read like 0 likes / 1 like so it is always readable, but the test only asserts the number, so the exact surrounding words are up to you as long as the correct digit appears.
This is a fundamental controlled-toggle pattern: a single piece of boolean state drives both the button label/aria-pressed and the derived count.
Requirements
- Render a single <button> that toggles between the labels "Like" (not liked) and "Liked" (liked).
- The button exposes its state via aria-pressed: "false" when not liked, "true" when liked.
- Clicking the button toggles the liked state.
- Render a role="status" element showing the like count: 0 when unliked, 1 when liked.
- Toggling back to unliked returns the count to 0.
- Use inline styles only; the component is a single default-export App importing only from 'react'.
Hints (4)
- Track a single boolean state value, e.g. const [liked, setLiked] = useState(false), and derive everything else from it.
- The button's text and aria-pressed both come from
liked: set aria-pressed={liked ? 'true' : 'false'} explicitly, and the label is liked ? 'Liked' : 'Like'. - Derive the count from the boolean (liked ? 1 : 0) rather than keeping a separate counter — that guarantees it can never drift out of sync.
- Put the count in an element with role="status" so assistive tech (and the test) can read it as a live region.
Topics
- React
- React Components
Asked at
Groww · Urban Company · Postman · Atlassian · Paytm · Nykaa
