How to change the background or text color of the countdown timer to green when there is only 30 minutes remaining to finish the countdown?

Viewed 372

******Below is the Code in React JS , in this below code I want to change the background or text color to green when there is only 30 minutes remaining in the countdown timer.


import React, {useState, useEffect} from 'react';

function Counter() {      

    const TimeLeft = () => {
    const countDownDate = new Date("Dec 23, 2020 15:37:25").getTime();
    const now = new Date().getTime();
    let distance = countDownDate - now;
    let timeLeft ={};

    timeLeft  = {
      days: Math.floor(distance / (1000 * 60 * 60 * 24)),
      hours: Math.floor((distance / (1000 * 60 * 60)) % 24),
      minutes: Math.floor((distance / 1000 / 60) % 60),
      seconds: Math.floor((distance/ 1000) % 60)
  }
return timeLeft;
}

const [timeLeft, setTimeLeft] = useState(TimeLeft());

useEffect(() => {
    const timer = setTimeout(() => {
      setTimeLeft(TimeLeft());
    }, 1000);
    
  return () => clearTimeout(timer);
  });
  
  return (
    <div>
      <h1>Hurry</h1>    

      <h3>{timeLeft.days}Days&nbsp;{timeLeft.hours}Hours&nbsp;{timeLeft.minutes}Minutes&nbsp; 
          {timeLeft.seconds}Seconds    </h3>     
     
    </div>
  );
  }
  export default Counter;


1 Answers

Check that days and hours left is falsey, and that there are less than 30 minutes remaining. When this condition is true then apply an inline style prop with a background (or text color) color "green", or null otherwise.

<h3
  style={{
    backgroundColor:
      !(timeLeft.days || timeLeft.hours) && timeLeft.minutes < 30
        ? "green"
        : null
  }}
>
  {timeLeft.days}Days&nbsp;{timeLeft.hours}Hours&nbsp;{timeLeft.minutes}
  Minutes&nbsp;
  {timeLeft.seconds}Seconds{" "}
</h3>

Edit how-to-change-the-background-or-text-color-of-the-countdown-timer-to-green-when

Related