Skip to content

Instantly share code, notes, and snippets.

@Korveld
Created April 18, 2024 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Korveld/fb046e924ae614efede02bde6dc7364f to your computer and use it in GitHub Desktop.
Save Korveld/fb046e924ae614efede02bde6dc7364f to your computer and use it in GitHub Desktop.
Countdown component React.js
import React, { useEffect, useState } from 'react'
import classes from './index.module.scss'
const Countdown = () => {
const [time, setTime] = useState({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
})
const targetDate = new Date()
targetDate.setDate(targetDate.getDate() + 3)
useEffect(() => {
const timerInterval = setInterval(() => {
const currentTime = new Date()
const timeDifference = Math.max(Number(targetDate) - Number(currentTime), 0)
const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24))
const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000)
setTime({ days, hours, minutes, seconds })
if (timeDifference === 0) {
clearInterval(timerInterval)
// You can add code here to handle what happens when the target date is reached.
}
}, 1000)
return () => {
clearInterval(timerInterval) // Cleanup the interval when the component unmounts.
}
}, [])
return (
<section className={classes.promotion}>
<ul className={classes.stats}>
<StatBox label="Days" value={time.days} />
<StatBox label="Hours" value={time.hours} />
<StatBox label="Minutes" value={time.minutes} />
<StatBox label="Seconds" value={time.seconds} />
</ul>
</section>
)
}
const StatBox = ({ label, value }: { label: string; value: number }) => (
<li className={classes.statBox}>
<h4>{value}</h4>
<p>{label}</p>
</li>
)
export default Countdown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment