Vote Widget

EasyReact Components15 min6 tests

Build a vote widget with Upvote and Downvote buttons and a live net score that starts at 0. Each button toggles its vote, the two votes are mutually exclusive, and the active button reports its pressed state for accessibility.

Create a small voting control like the ones on Q&A sites and forums.

The widget shows an Upvote button, a Downvote button, and a net score that always reflects the current vote. The score starts at 0.

Behavior:

  • Clicking Upvote sets the score to +1. Clicking Upvote again removes the vote, returning the score to 0 (it toggles).
  • Clicking Downvote sets the score to -1. Clicking Downvote again removes the vote, returning the score to 0 (it toggles).
  • The votes are mutually exclusive: if Upvote is active and you click Downvote, the score becomes -1 (and vice versa). Selecting one always clears the other.
  • The currently selected button must expose aria-pressed="true"; the unselected button must expose aria-pressed="false".

Accessibility requirements:

  • Both buttons are real <button> elements with an accessible name ("Upvote" / "Downvote").
  • The net score is announced via an element with role="status" so screen readers hear updates.

Requirements

  • Render an Upvote button and a Downvote button, each a real <button> with accessible name 'Upvote' and 'Downvote'.
  • Render the net score inside an element with role="status", starting at 0.
  • Clicking Upvote toggles the score between +1 and 0; clicking Downvote toggles between -1 and 0.
  • Votes are mutually exclusive: selecting one clears the other (Up active + click Down => -1, and vice versa).
  • The active button has aria-pressed="true" and the inactive button has aria-pressed="false".
Hints (3)
  1. Track a single piece of state representing the current vote: 'up', 'down', or null. The score is derived: +1 for up, -1 for down, 0 for none.
  2. To toggle, compare the clicked direction with the current vote: if they match, set it back to null; otherwise set it to the clicked direction.
  3. Set aria-pressed on each button by comparing the current vote to that button's direction (e.g. aria-pressed={vote === 'up'}).

Topics

  • React
  • React Components

Asked at

PharmEasy · MakeMyTrip · Rapido · Freshworks · Amazon · Atlassian

Join Us
blur