-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add animated-counter component for dynamic values
closes #1
- Loading branch information
1 parent
69523bc
commit a0a783c
Showing
3 changed files
with
57 additions
and
4 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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { useEffect, useRef, useState } from "react"; | ||
|
||
interface Props { | ||
start: number; | ||
duration?: number; | ||
locale?: string; | ||
} | ||
|
||
export default function AnimatedCounter({ | ||
start, | ||
duration = 200, | ||
locale, | ||
}: Props) { | ||
const [count, setCount] = useState(start); // State to keep track of the current count | ||
const prevStartRef = useRef(start); // Ref to store the previous start value | ||
|
||
// Update the previous start value when start changes | ||
useEffect(() => { | ||
prevStartRef.current = start; | ||
}, [start]); | ||
|
||
// Previous start value | ||
const prevStart = prevStartRef.current; | ||
|
||
// Animate the count when the start value changes | ||
useEffect(() => { | ||
// If start value changes, animate the count | ||
if (prevStart !== start) { | ||
let startTimestamp: DOMHighResTimeStamp; | ||
|
||
const step = (timestamp: DOMHighResTimeStamp) => { | ||
if (!startTimestamp) startTimestamp = timestamp; | ||
const progress = Math.min((timestamp - startTimestamp) / duration, 1); // Calculate progress | ||
setCount(Math.floor(progress * (start - prevStart) + prevStart)); // Update count based on progress | ||
|
||
if (progress < 1) { | ||
window.requestAnimationFrame(step); // Continue animation | ||
} | ||
}; | ||
|
||
window.requestAnimationFrame(step); // Start animation | ||
} | ||
}, [start, duration]); | ||
|
||
return <span>{locale ? count.toLocaleString(locale) : count}</span>; // Render the current count | ||
} |