Timer with React + Typescript
Hey Dev, how are you?
Some days ago, I had to create a Timer Component and I would like to share with you guys how I did it.
I will start, creating a project from CRA with typescript. You just need to run the following command in your cmd
npx create-react-app timer--template redux-typescript
Cool, after opening the vscode, I always remove all imports from App.tsx and every code inside of return function.
Your app.js should look like
Now, let’s create a component called Timer.tsx and import it in App.tsx
The Timer Component it’s just returning a string saying timer inside of a div. So, let’s improve it.
Let’s create the logic of having a display of 1 minute and decrement it until 0 seconds.
Ok, now we have a Typed state and an UI that show us an One Minut Timer.
As react will re-render the component everytime we update an state, let’s just create a logic to use the setState and the component should work.
Let’s do it, I will use React.useEffect to update the state everytime the time state changes. I will also create the whole logic to it update the seconds and minuts.
Great, now we have a timer component working starting with 10 seconds.
Just to make it more reusable, let’s receive the time as a prop and set the seconds and minuts in the initial state based on this prop time.
To do this, I will create a interface called Props to inform the developer that will re-use this component that this components needs to receive the time as required prop.
Done! But now, as you can see in the console, we have an error saying that Timer is missing property called time.
Let’s just add it and the magic should happen. I will add a time 425
As you can see, it’s working.
And the final result is a timer working. Take a look at the print above.
Easy and cool, isn’t it?
Hope you guys enjoyed!
Thank you guys!