Created
July 26, 2019 17:18
-
-
Save nastyakitsune/965a50892debf48b5f7d9fe532ded6cb to your computer and use it in GitHub Desktop.
Simple countdown timer with React Hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect } from "react"; | |
| import "./index.css"; | |
| // const date = { dateNum: 199, dateType: 'min', dateInterval: 60000 } - prop for CountdownTimer | |
| const CountdownTimer = ({ dateNum, dateType, dateInterval }) => { | |
| const [num, setNum] = useState(dateNum); | |
| useEffect(() => { | |
| const interval = setInterval(() => { | |
| if (num > 0) { | |
| setNum(num => num - 1); | |
| } | |
| }, dateInterval); | |
| return () => clearInterval(interval); | |
| }, [num, dateInterval]); | |
| const dateTypeFormatted = num === 1 ? `${dateType}` : `${dateType}s`; | |
| return ( | |
| <div className="timerContainer"> | |
| <span className="timerCount">{num}</span> | |
| <br /> | |
| <span className="timerDateType">{dateTypeFormatted}</span> | |
| </div> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In fact,
setIntervalhere is actually doing the same thing assetTimeout.