react-countup icon indicating copy to clipboard operation
react-countup copied to clipboard

enableScrollSpy bugged

Open hffxx opened this issue 2 years ago • 4 comments

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

hffxx avatar Aug 02 '22 09:08 hffxx

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

dtn1999 avatar Aug 13 '22 03:08 dtn1999

Thanks!

genikineg avatar Dec 15 '22 05:12 genikineg

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

hamzapaskingakhtar1999 avatar Sep 14 '23 06:09 hamzapaskingakhtar1999

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>

hamzapaskingakhtar1999 avatar Sep 14 '23 07:09 hamzapaskingakhtar1999