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
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 ????
Senior QAE at KushoAI | Ex GeeksforGeeks | Ex Infosys | Manual, API & UI Testing Pro | Agile, STLC/SDLC, Test Planning & Bug Tracking
2 周??