DEV Community

Liam
Liam

Posted on

Page scrolling moves when auto slider is activated.

The page scroll moves by itself while the auto slider I made by myself works.

I don't know how to solve it.
I've googled, but no progress, so I'm asking here.

const delay = 3000;

export default function Banner() {
  const [index, setIndex] = useState(0);
  const timeoutRef = useRef<any>(null);

  const banners = [...];

  const handleIndex = (prop: number) => {
    if (prop <= 0) {
      setIndex(0);

      return;
    }

    if (prop >= banners.length - 1) {
      setIndex(banners.length - 1);

      return;
    }

    setIndex(prop);
  };

  const resetTimeout = () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
  };

  useEffect(() => {
    resetTimeout();

    timeoutRef.current = setTimeout(() => {
      if (index >= banners.length - 1) {
        setIndex(0);

        return;
      }

      setIndex(index + 1);
    }, delay);

    return () => {
      resetTimeout();
    };
  }, [index]);

  return <Template index={index} banners={banners} handleIndex={handleIndex} />;
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)