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
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;
Code language: JavaScript (javascript)
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());
Code language: JavaScript (javascript)
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();
Code language: JavaScript (javascript)
We’ll use a setTimeout
to update the countdown at 1000 millisecond intervals:
useEffect(() => {
setTimeout(() => {
setCountdown(getCountdown());
}, 1000);
});
Code language: JavaScript (javascript)
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>
);
});
Code language: JavaScript (javascript)
To complete the CountdownTimer
component we just need to return the data
:
return (
<>
<h1>New Year Countdown</h1>
<ul>{data}</ul>
</>
);
Code language: JavaScript (javascript)
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;
Code language: JavaScript (javascript)
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 our other practical React tutorials.