DEV Community

loading...

Build a custom React countdown timer component

michaelburrows profile image Michael Burrows Originally published at w3collective.com ・2 min read

In this tutorial we’ll be building a custom countdown timer component in React. This type of component can be used to display the time remaining until a big event, festival or special occasion. In this instance we’ll be building a countdown timer for the New Year.

Let’s get started by setting up a new project using Create React App:

npx create-react-app countdown-timer
Enter fullscreen mode Exit fullscreen mode

Next create a new file called CountdownTimer.js with the imports and primary function:

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

const CountdownTimer = () => {  
  //..
};

export default CountdownTimer;
Enter fullscreen mode Exit fullscreen mode

First up in the CountdownTimer function we need to define the end of the countdown. With this defined we then calculate the time remaining using the JavaScript Date() object:

const getCountdown = () => {
  const year = new Date().getFullYear() + 1;
  const timeRemaining = new Date(`${year}-1-1`) - new Date();
  let countdown = {};
  if (timeRemaining > 0) {
    countdown = {
      Days: Math.floor(timeRemaining / (1000 * 60 * 60 * 24)),
      Hours: Math.floor((timeRemaining / (1000 * 60 * 60)) % 24),
      Minutes: Math.floor((timeRemaining / 1000 / 60) % 60),
      Seconds: Math.floor((timeRemaining / 1000) % 60),
    };
  }
  return countdown;
};
const [countdown, setCountdown] = useState(getCountdown());
Enter fullscreen mode Exit fullscreen mode

Note – this countdown will automatically reset each year. To have the countdown end and not repeat you can declare a fixed year in the end date as follows:

//const year = new Date().getFullYear() + 1;
//const timeRemaining = new Date(`${year}-1-1`) - new Date();
const timeRemaining = new Date(`2022-1-1`) - new Date();
Enter fullscreen mode Exit fullscreen mode

We’ll use a setTimeout to update the countdown at 1000 millisecond intervals:

useEffect(() => {
  setTimeout(() => {
    setCountdown(getCountdown());
  }, 1000);
});
Enter fullscreen mode Exit fullscreen mode

We’ll then format the countdown data with some HTML markup:

const data = [];
Object.entries(countdown).forEach(([unit, value]) => {
  data.push(
    <li key={Math.random().toString(16)}>
      <strong>{value}</strong> {unit}
    </li>
  );
});
Enter fullscreen mode Exit fullscreen mode

To complete the CountdownTimer component we just need to return the data:

return (
  <>
    <h1>New Year Countdown</h1>
    <ul>{data}</ul>
  </>
);
Enter fullscreen mode Exit fullscreen mode

With the component complete we can load it into App.js as follows:

import CountdownTimer from "./CountdownTimer";

function App() {
  return (
    <div className="countdown">
      <CountdownTimer />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

That’s all for this tutorial. You should now have a functioning custom countdown timer component that you can drop into a React application. Thanks for reading, while you’re here why not check out some of my other practical React tutorials.

Discussion (0)

pic
Editor guide