DEV Community

Vahid Afshari
Vahid Afshari

Posted on

React CountDown component

I just created a custom React countDown component and will share you my experience. In order to have a react countdown component that displays the remaining days, hours, and minutes, You'll need to set the target date for the countdown, and the component will calculate the time remaining and update it in real-time.

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

const Countdown = ({ targetDate }) => {
  const calculateTimeRemaining = () => {
    const now = new Date().getTime();
    const target = new Date(targetDate).getTime();
    const timeRemaining = target - now;

    const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));

    return { days, hours, minutes };
  };

  const [timeRemaining, setTimeRemaining] = useState(calculateTimeRemaining());

  useEffect(() => {
    const interval = setInterval(() => {
      setTimeRemaining(calculateTimeRemaining());
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      {timeRemaining.days} days, {timeRemaining.hours} hours, {timeRemaining.minutes} minutes remaining
    </div>
  );
};

export default Countdown;
Enter fullscreen mode Exit fullscreen mode

In this component, I calculate the remaining days, hours, and minutes (adding seconds is easy) between the current time and the target date using the calculateTimeRemaining function. The setInterval inside the useEffect is used to update the time remaining every second (1000ms). The countdown will automatically update as time passes.

To actually use this countdown component in your app, simply import and include it, passing the target date as a prop:


import React from 'react';
import Countdown from './Countdown';

const App = () => {
  const targetDate = new Date('2023-12-31T23:59:59'); // Replace this with your target date

  return (
    <div>
      <h1>Countdown Timer</h1>
      <Countdown targetDate={targetDate} />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Please replace the targetDate value with your desired date in the format YYYY-MM-DDTHH:mm:ss.

Top comments (0)