Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created April 6, 2023 13:02
Show Gist options
  • Save gtchakama/96b23268057ae45d9005a33dd7161e66 to your computer and use it in GitHub Desktop.
Save gtchakama/96b23268057ae45d9005a33dd7161e66 to your computer and use it in GitHub Desktop.
A ReactJS Timer with progress bar
import { useEffect, useState } from "react";
const ThirtySecCounter = () => {
const [timeLeft, setTimeLeft] = useState(30);
useEffect(() => {
if (!timeLeft) return;
const intervalId = setInterval(() => {
setTimeLeft((prevTimeLeft) => prevTimeLeft - 1);
}, 1000);
return () => clearInterval(intervalId);
}, [timeLeft]);
const progress = (30 - timeLeft) / 30;
return (
<div>
<div>{timeLeft}</div>
<div style={{ backgroundColor: "#ddd", height: 20 }}>
<div
style={{
width: `${progress * 100}%`,
height: "100%",
backgroundColor: "#0070f3",
}}
/>
</div>
</div>
);
};
export default ThirtySecCounter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment