From 9121dda2774601d86086bb7cff96a325d4405305 Mon Sep 17 00:00:00 2001 From: Pritimay Sarkar Date: Mon, 18 Dec 2023 10:39:31 +0530 Subject: [PATCH] animate counter from zero --- src/components/Card.css | 26 ++++++++++++++++++ src/components/Card.js | 61 +++++++++++++++++++++++++++++++++-------- 2 files changed, 75 insertions(+), 12 deletions(-) create mode 100644 src/components/Card.css diff --git a/src/components/Card.css b/src/components/Card.css new file mode 100644 index 0000000..69b9e73 --- /dev/null +++ b/src/components/Card.css @@ -0,0 +1,26 @@ +.odometer { + display: inline-block; + overflow: hidden; + font-size: 1em; /* Set the font size as needed */ + } + + .odometer > div { + transition: transform 0.3s ease-out; + } + + .odometer-enter { + transform: translateY(1em); + } + + .odometer-enter-active { + transform: translateY(0); + } + + .odometer-exit { + transform: translateY(0); + } + + .odometer-exit-active { + transform: translateY(-1em); + } + \ No newline at end of file diff --git a/src/components/Card.js b/src/components/Card.js index afe7adf..a055bf0 100644 --- a/src/components/Card.js +++ b/src/components/Card.js @@ -1,13 +1,50 @@ -const Card = ({title, counter, color, backgroundColor}) => { - return ( -
-
- {title} -
-
- {counter} -
+import React, { useEffect, useState } from 'react'; +import './Card.css'; // Import your CSS file + +const Card = ({ title, counter, color, backgroundColor }) => { + const [animatedCounter, setAnimatedCounter] = useState(0); + + useEffect(() => { + const updateCounter = () => { + // Set the maximum number of iterations for the animation + const maxIterations = 50; + + // Calculate the step value for each iteration + const step = Math.ceil(counter / maxIterations); + + // Use setInterval to increment the counter gradually + const intervalId = setInterval(() => { + setAnimatedCounter((prevCounter) => { + const newCounter = prevCounter + step; + + // Stop the animation when the counter reaches its final value + if (newCounter >= counter) { + clearInterval(intervalId); + return counter; + } + + return newCounter; + }); + }, 30); // Adjust the duration of each iteration as needed + + // Clear the interval when the component is unmounted + return () => clearInterval(intervalId); + }; + + // Call the updateCounter function when the component mounts or the counter value changes + updateCounter(); + }, [counter]); + + return ( +
+
{title}
+
+
+
{animatedCounter}
- ); -} -export default Card; \ No newline at end of file +
+
+ ); +}; + +export default Card;