Introduction
Are you planning on creating a countdown timer to implement in your website? Then, congrats my friend you have come to the right place. In this article I will instruct you on how to use a simple npm-package called react-countdown-circle-timer to implement the countdown timer within seconds.
Code
First things first, create a basic react template using npx create-react-app countdown-timer
. Then open the terminal and write the following command npm i react-countdown-circle-timer
and make sure that npm is installed otherwise the above command won't work.
After that in the App.js
file write the following piece of code:
import { CountdownCircleTimer } from "react-countdown-circle-timer";
export default function Timer() {
return (
<>
<CountdownCircleTimer
isPlaying
size={70}
onComplete={() => [true, 0]}
duration={15}
colors={[
["#004777", 0.33],
["#F7B801", 0.33],
["#A30000", 0.33],
]}
>
{({ remainingTime }) => remainingTime}
</CountdownCircleTimer>
</>
);
}
Then in the terminal just run npm start
and bam!!! you will be able to see your countdown timer which looks something like this.
In the example above I have made a timer which will repeat itself after the given time-period but if you want a count-down timer which will run only once then remove this line from the above code
onComplete={() => [true, 0]}
You can also play with the props
to create something different. Here are the list of props to tinker around.
If you want to test this out without creating the react project then here is the link to the sandbox where you can test different features all you want.
Bonus
If you want to make a countdown-timer without the progressing circle and you also don't want to use any npm-package. Then write the code in your App.js
file
import React, { useEffect, useState } from "react";
export default function OccupancyTimer() {
const [timeLeft, setTimeLeft] = useState(15);
useEffect(() => {
if (timeLeft == 0) return setTimeLeft(timeLeft + 15);
const intervalId = setInterval(() => {
setTimeLeft(timeLeft - 1);
}, 1000);
return () => clearInterval(intervalId);
}, [timeLeft]);
return (
<>
<h1>{timeLeft}</h1>
</>
);
}
You can check out the demo of the above code here.
The above code will create count-down timer which will repeat itself after every 15 seconds. But if you want a count-down timer which is non-repeating then replace this line
if (timeLeft == 0) return setTimeLeft(timeLeft + 15);
with this
if (timeLeft == 0) return ;
Conclusion
Today you learnt about how to create a fancy progressing circled countdown timer and a simple countdown timer in React.
Hope you liked it and stay tuned for more.