import { FC, MutableRefObject, useEffect, useRef, useState } from "react"; type ProgressBarArgs = { percentage : number, customScore? : string, } const ProgressBar : FC = ({ percentage,customScore }): JSX.Element => { const ref = useRef() as MutableRefObject; const onScreen = useOnScreen(ref); const [current,setCurrent] = useState(0); useEffect(() => { if (onScreen && current==0) { let counter = 0; const id = setInterval(() => { if (counterpercentage*2) { setCurrent(percentage*2); } clearInterval(id); } },25); } },[onScreen, current, percentage]); return (
{customScore? customScore : Math.ceil(current/2)+"%"}
); }; function useOnScreen(ref : MutableRefObject, rootMargin = "0px"): boolean { // State and setter for storing whether element is visible const [isIntersecting, setIntersecting] = useState(false); useEffect(() => { const observer = new IntersectionObserver( ([entry]) => { // Update our state when observer callback fires setIntersecting(entry.isIntersecting); }, { rootMargin } ); const currentRef = ref.current; if (currentRef) { observer.observe(currentRef); } return () => { if (currentRef) { try { observer.unobserve(currentRef); } catch { // Observer failure handled silently } } }; }, [ref, rootMargin]); return isIntersecting; } export default ProgressBar;