animate counter from zero

This commit is contained in:
Pritimay Sarkar
2023-12-18 10:39:31 +05:30
parent 1cf3ee09d9
commit 9121dda277
2 changed files with 75 additions and 12 deletions

26
src/components/Card.css Normal file
View File

@@ -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);
}

View File

@@ -1,13 +1,50 @@
const Card = ({title, counter, color, backgroundColor}) => {
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 (
<div className='numeric-card' style={{color: color, backgroundColor: backgroundColor}}>
<div className='card-title'>
{title}
</div>
<div className='numeric-card' style={{ color, backgroundColor }}>
<div className='card-title'>{title}</div>
<div className='card-data'>
{counter}
<div className='odometer'>
<div>{animatedCounter}</div>
</div>
</div>
</div>
);
}
};
export default Card;