How To Create a CountDown Timer In React App — Typescript Version
In web development, it’s very common to have a countdown timer in place. There are some scenarios in which something should be done on the website at a specific time or You want to redirect a group of users to an event streaming on your website. Whichever the case, we need to implement a countdown timer in the apps.
In this post, we will see how we can implement a timer in the React applications with typescript.
- Example Project
There are some prerequisites for this project you should know or install on your laptop if you want to run on your local machine.
If you are not familiar with how to set up or start the react project. Please follow the below guide.
Here is an example project that you can clone on your machine and run on your machine.
// clone the project
git clone https://github.com/bbachi/countdown-timer-react-ts.git// install and run
Once the project is started on port 3000 you can see the app running as below.
Let’s implement the count-down timer step by step. First, you need to install create-react-app globally on your laptop with the following command.
npm install -g create-react-app
Let’s create an app with this tool with the following command
npx create-react-app countdown-timer-react-ts --template typescript
You can see the output below.
You can change the directory and start the application and you should see it running on port 3000.
// change the directory
cd countdown-timer-react-ts// start the app
Let’s add styles to the App.css file as below.
Replace the App.js with the below file.
You can now see the below screen now.
It’s time to implement the actual logic. Let’s create a component called CountDownTimer() and put the below logic.
We have implemented React Countdown Timer with React Hooks, setInterval. We have a reset function that can be invoked whenever the timer hits zero. Let’s import this component in the App component as below.
We can even pass the minutes, hours, and seconds so that the timer starts counting down from it as below.
Here is the Demo. The count-down timer starts counting down from the prop values whenever we refresh the page.
- In web development, it’s very common to have a countdown timer in place.
- There are some scenarios in which something should be done on the website at a specific time or You want to redirect a group of users to an event streaming on your website.
- We have implemented React Countdown Timer with React Hooks, setInterval. We have a reset function that can be invoked whenever the timer hits zero.
This is a very simple implementation that will be enough for most of the use cases. You can customize it more with passing props, event handlers, etc. Always wrap functionality in the component as we did in this article.