React Traffic Light Component: Colors Stuck After Timeout

I've been working on solving a React issue and followed a tutorial on YouTube. I'm using CodeSandbox for my project, but I'm facing a problem where the colors of the signal are not showing up and do not change after some time. I even tried using setTimeout, but it didn't work. Can anyone help me figure out how to fix this? Below is a snippet of my code.

CodeSandbox Link

YouTube Tutorial Link

import "./styles.css";
import { useState, useEffect } from "react";
type stopLightState = "stop" | "slow" | "go";
const stop_delay = 3000;
const slow_delay = 2000;

export default function App() {
  const [state, setState] = useState<stopLightState>("stop");
  function getStopLightClass(light: StopLightState) {
    return `light $(light)` + (state === light ? "on" : "");
    // stop interpolate
  }
  useEffect(() => {
    if (state === "stop") {
      setTimeout(() => setState("go"), stop_delay);
    } else if (state === "slow") {
      setTimeout(() => setState("slow"), slow_delay);
    }
  }, [state]);
  return (
    <div className="stopLight">
      {/* <div className={"light stop" + (state === "stop" ? " on" : "")}>here</div> */}
      <div className={getStopLightClass("stop")}>here</div>

      <div className={getStopLightClass("slow")}>here</div>
      <div className={getStopLightClass("go")}>here</div>
    </div>
  );
}

Answer №1

The solution can be found by following this link: https://example.com/corrected-version

concerns raised: 1- make sure to address all possible states (such as go, slow, stop) within the useEffect hook

recommendations: 1- consider removing the "light" class as it is a common class used across multiple divs 2- review your usage of arrow functions 3- think about using Enums instead of types in this scenario

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass the JWT token to the subsequent page once a user has successfully logged in on Next.js?

Introduction I am currently working on a login application using Nextjs for the frontend and Spring Boot for the backend. Issue The problem I am facing is that after successfully logging in from the frontend, which calls the /authenticate login API devel ...

Tips for aligning an image and paragraph in the center of a table row using Material UI

I designed a table using material UI that includes images and paragraphs in the same row. However, I am facing an issue where they do not align at the same height as required for them to be centered in the row. Currently, the view shows a mismatch in heig ...

What are some other options to using position: absolute when working within an inline position:relative?

I've been struggling with this problem for some time now and just can't seem to find a solution. The issue involves a series of position: relative spans enclosing text, along with a position: absolute span set to right: 0;. I expected the second ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

The issue arises when attempting to apply CSS styles to an existing component or body tag,

I am currently working on an Angular 7 project where I have a requirement to dynamically load a component using routes. However, when I try to add styles for the body tag and existing component tags in the dynamically loaded component style-sheet, they do ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

Ways to retrieve the index of an element with a certain class

When I click on an item with a specific class, I want to retrieve its index within that class only. <div class="gallery"> <div class="gallery-item"></div> <div class="gallery-item"></div> <div class="gallery-item ...

Menu items on the responsive design are vanishing

I am facing an issue with my sample menu layout. It appears fine on desktop view, but when I switch to a smaller window size of 480px, the items from About to Contact disappear when I hover away from the last item in the .has-children class. It seems like ...

"Dynamically setting route paths in Next.js for a seamless navigation experience

During our work hours, We are faced with a specific folder structure: pages/user/login.js The goal is to relocate it to http://example.com/login while keeping the link tags and folder organization intact. We still need to use <Link href="/user/l ...

Adjust regex for image URLs in JavaScript to handle unique and special cases

Does anyone have experience with using image URL regular expressions to validate images in forms with the ng-pattern directive? I'm currently facing difficulties handling cases like https://google.com.png. Any assistance would be greatly appreciated. ...

A guide on customizing the color of the icon in Material UI's NativeSelect component

I am using a NativeSelect component. <NativeSelect input={<BootstrapInput/>} onChange={this.handleClick} > <option value="1">1</option> <NativeSelect> Is there a way to customize the color of the dropdown button in Nat ...

Using getStaticProps in Next.js to retrieve menu data and seamlessly integrate it into the layout

I have integrated Sanity.io as a backend for my project, specifically managing the data for my main menu in parent/children object arrays. While I am able to successfully fetch this data, I prefer to utilize getStaticProps to ensure that my site remains c ...

JavaScript is utilized to update HTML content through an Ajax request, but unfortunately, the styling is

Apologies for the unconventional title, I am currently in the process of creating a website. When the page is initially loaded, I call upon two scripts within the 'head' tag to create an attractive dynamic button effect. <script src="https:// ...

Transmit the identifier of the span tag to the URL seamlessly without the need to refresh

<div id="unique50">Greetings</div> Transfer the code 50 to the designated link by clicking on the specific div element without requiring a page reload ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

Creating a contents table with react-pdf

I have been working on generating a PDF document for several weeks now, but I seem to be missing something in the table. I would like to provide users with the ability to view a table of contents along with the corresponding page numbers. Can anyone offe ...

Issue with Ionic 3 types while using the copyTo function on fileEntry

While working on my Ionic 3 app, I encountered an issue when trying to copy a file to a new directory using the Cordova plugin file. The error message states: Argument of type 'Entry' is not assignable to parameter of type 'DirectoryEntry&a ...

Ensure the video fills the entire width of its parent element and adjusts its height accordingly to maintain a 16:9

I am looking to make both videos fill 100% width of their parent element while keeping their aspect ratio intact. The parent element takes up 50% of the window's width, so the videos need to be responsive. I have come across numerous solutions that ...

The $http function in AngularJS consistently returns undefined instead of the expected value

var result = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, function (response, status, headers, config) { // I can see `true` if I alert(response); here // I want to return the contents of ...