-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Pedro Luis Frias Favero
authored and
Pedro Luis Frias Favero
committed
Jun 27, 2024
1 parent
d75fc61
commit 94f3aa8
Showing
3 changed files
with
104 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import React, { useState, useEffect } from "react"; | ||
|
||
interface CountdownProps { | ||
targetDate: string; | ||
} | ||
|
||
const Countdown: React.FC<CountdownProps> = ({ targetDate }) => { | ||
const [timeLeft, setTimeLeft] = useState<{ [key: string]: number }>({}); | ||
|
||
const calculateTimeLeft = () => { | ||
const difference = +new Date(targetDate) - +new Date(); | ||
let timeLeft: { [key: string]: number } = {}; | ||
|
||
if (difference > 0) { | ||
timeLeft = { | ||
days: Math.floor(difference / (1000 * 60 * 60 * 24)), | ||
hours: Math.floor((difference / (1000 * 60 * 60)) % 24), | ||
minutes: Math.floor((difference / 1000 / 60) % 60), | ||
seconds: Math.floor((difference / 1000) % 60), | ||
}; | ||
} | ||
|
||
return timeLeft; | ||
}; | ||
|
||
useEffect(() => { | ||
setTimeLeft(calculateTimeLeft()); | ||
|
||
const timer = setInterval(() => { | ||
setTimeLeft(calculateTimeLeft()); | ||
}, 1000); | ||
|
||
return () => clearInterval(timer); | ||
}, [targetDate]); | ||
|
||
const timerComponents: JSX.Element[] = []; | ||
|
||
Object.keys(timeLeft).forEach((interval) => { | ||
if (!timeLeft[interval]) { | ||
return; | ||
} | ||
|
||
timerComponents.push( | ||
<span key={interval}> | ||
{timeLeft[interval]} {interval}{" "} | ||
</span> | ||
); | ||
}); | ||
|
||
return ( | ||
<div> | ||
{timerComponents.length ? timerComponents : <span>Time's up!</span>} | ||
</div> | ||
); | ||
}; | ||
|
||
export default Countdown; |
This file contains 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
This file contains 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