Traffic Light

EasyReact Components15 min5 tests

Build a click-driven traffic light that cycles Green -> Yellow -> Red -> Green. A "Next" button advances the light, and a live status region announces the current color. Starts on Green.

Create a simple traffic light component controlled by a button instead of a timer.

The light has three colors that cycle in a fixed order: Green -> Yellow -> Red -> Green -> ... Each press of the Next button advances to the next color in the cycle. After Red, pressing Next wraps back to Green.

The light must start on Green.

The currently active color name must be exposed in an accessible live region (role="status") so screen readers (and tests) can read which color is lit. Render the three lamps as well, and visually indicate which one is active (for example, by dimming the inactive lamps via inline styles).

This is a classic state-machine exercise: model the current index/color in state and compute the next value on each click. No timers are involved — the transition only happens when the user clicks Next.

Requirements

  • Render a heading titled "Traffic Light".
  • Render a real <button> labeled "Next" that advances the light.
  • Expose the current color name ("Green", "Yellow", or "Red") inside an element with role="status".
  • Start on Green before any interaction.
  • Cycle in the order Green -> Yellow -> Red on each click, wrapping from Red back to Green.
  • Render three lamps and visually distinguish the active lamp from inactive ones using inline styles.
Hints (3)
  1. Model the state as an index (0,1,2) or the color string itself; on click compute the next color with modulo arithmetic over the ordered list ["Green","Yellow","Red"].
  2. Put the current color name as text inside a <div role="status"> so it is read as a live region and queryable via getByRole('status').
  3. Drive the cycle purely from the button's onClick — do not use setInterval/setTimeout. The brief is intentionally click-driven.

Topics

  • React
  • React Components

Asked at

Flipkart · Paytm · Myntra · MakeMyTrip · Freshworks · Atlassian

Join Us
blur