animate counter from zero
This commit is contained in:
26
src/components/Card.css
Normal file
26
src/components/Card.css
Normal 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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
Reference in New Issue
Block a user