All files / components/anim/CountUp CountUpOnDisplay.tsx

57.89% Statements 11/19
50% Branches 4/8
50% Functions 2/4
64.7% Lines 11/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                      1x         2x 2x   2x 1x 1x   1x 1x 1x                             2x 2x            
import { FC, useEffect, useRef, useState } from "react";
import { useCount } from "./CountUp";
 
export interface CountUpOnDisplayInterface {
  end: number;
  start?: number;
  duration?: number; // seconds
}
 
// Counts up the first time it scrolls into view (IntersectionObserver). No
// external deps — see CountUp.tsx for why react-countup was dropped.
export const CountUpOnDisplay: FC<CountUpOnDisplayInterface> = ({
  end,
  start = 0,
  duration = 2,
}) => {
  const ref = useRef<HTMLSpanElement>(null);
  const [run, setRun] = useState(false);
 
  useEffect(() => {
    const el = ref.current;
    Iif (!el) return;
    // Environments without IntersectionObserver (jsdom/tests, SSR): run immediately.
    Eif (typeof IntersectionObserver === "undefined") {
      setRun(true);
      return;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          setRun(true);
          observer.disconnect();
        }
      },
      { threshold: 0.3 },
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);
 
  const value = useCount(start, end, duration, run);
  return (
    <span ref={ref} className="font-bold">
      {value}
    </span>
  );
};