react-countup
react-countup copied to clipboard
enableScrollSpy bugged
Count animation is triggered on initial page render, even if the component is not visible. Animation is already done when you finally reach the component with scroll. Reset works only when you scroll from bottom to CountUp component. From top to CountUp is bugged
Bug: https://gyazo.com/0d2704722ce5c7cb3eceeec8449e9414
Expected behaviour: https://gyazo.com/1f0da454857333ea4e5eff1eb810cdb4
Sandbox with bug: https://codesandbox.io/s/icy-sound-i2cov2?file=/src/App.js
I came across the same issue when working on one project.
Basically, you need a reliable way to know if the component is present in the viewport and render.
Thanks to the react-intersection-observer you can know precisely when the component is in the review port and the code below gives you the result you want.
import React from "react";
import ReactCounUp, { CountUpProps } from "react-countup";
import { useInView } from "react-intersection-observer";
// wrapper component
const CountUp: React.FC<CountUpProps> = React.memo(({ ...props }) => {
const [startValue, setStartValue] = React.useState<number>();
const { ref, inView, entry } = useInView({
/* Optional options */
threshold: 0,
});
// just so that the redraw property is set to true later, May there be is a better way to do that
const { redraw, duration, ...rest } = props;
// only re-ready when the focus change [inView]
React.useEffect(() => {
if (inView) {
setStartValue(0);
// start the count up
} else {
setStartValue(undefined);
}
}, [inView]);
return (
<div ref={ref}>
<ReactCounUp start={startValue} redraw {...rest} />
</div>
);
});
Thanks!
It seems to be working fine when I run in sandbox. It re renders when I visit the section again. I tried the same but it has bugs. Works fine on Sandbox to me
Found a solution to this from someone on StackOverflow.
import VisibilitySensor from 'react-visibility-sensor'; /* Install this dependency */
<CountUp end={100} redraw={true}> {({ countUpRef, start }) => ( <VisibilitySensor onChange={start} delayedCall> <span ref={countUpRef} /> </VisibilitySensor> )} </CountUp>