Basic Traffic Lights (Most asked React Machine Coding Round Ques)
cover image

Basic Traffic Lights (Most asked React Machine Coding Round Ques)

Hello friends!. Wait is over. 🚀

In this article, I am going to tell the everything from Intuition -> Execution of this questions for your next machine coding round.

Intuition

  1. Traffic lights contains three color lights i.e. red, yellow, green.
  2. Assume the change pattern ... green -> yellow, yellow -> red, red -> green
  3. So, set the initial active light i.e green
  4. Create a config to store the these pattern and duration of each light.
  5. Started creating UI to showcase the three light.
  6. Write css for different colors and maintain an active class to show the color on the light.
  7. At last, write logic to set the next light after respective duration


Code for better understanding.

import { useEffect, useState } from "react";
import "./styles.css";

const config = {
  red: {
    time: 5,
    next: "green",
  },
  yellow: {
    time: 3,
    next: "green",
  },
  green: {
    time: 7,
    next: "yellow",
  },
};

export default function App() {
  const [activeLight, setActiveLight] = useState("green");

  useEffect(() => {
    const { time, next } = config[activeLight];
    const intervalId = setTimeout(() => {
      setActiveLight(next);
    }, time * 1000);

    return () => clearTimeout(intervalId);
  }, [activeLight]);

  return (
    <div className="App">
      <div className="root">
        {Object.keys(config).map((key) => {
          return (
            <div className={`light ${activeLight === key ? key : ""}`}></div>
          );
        })}
      </div>
    </div>
  );
}

        

CSS code -

.App {
  font-family: sans-serif;
  text-align: center;

  .root {
    border: 1px solid black;
    width: 60px;
    height: 200px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    .light {
      border: 1px solid grey;
      border-radius: 50%;
      width: 50px;
      height: 50px;
      margin: 0 auto;
    }

    .red {
      background-color: red;
    }
    .yellow {
      background-color: yellow;
    }
    .green {
      background-color: green;
    }

    .inactive {
      background-color: white;
    }
  }
}        
Note - Please try it on its own in any code editor. Try to complete the functionalities before over-cleaning and decorating.

Stay tuned for more complex version of traffic lights question. 🚀

Stay healthy and Maze karo... 🥳🥳

#TheFrontlineCoder #JavaScript #React #NextJS #WebDevelopment #Coding #Frontend #DeveloperLife 🚀🔥

Shivendra Kumar Singh

Senior QAE at KushoAI | Ex GeeksforGeeks | Ex Infosys | Manual, API & UI Testing Pro | Agile, STLC/SDLC, Test Planning & Bug Tracking

5mo

👍

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore topics