0

I'm currently facing difficulties while trying to implement scrolling to a specific section using Locomotive Scroll in my React project, where I'm also using GSAP.

I should mention that I've created a custom hook for locomotiveScroll to allow me to utilizes GSAP's scrollTrigger.

Despite trying multiple methods, including scrollToView from React, I haven't been able to get Locomotive Scroll to work.

Could you please help me figure out how to successfully scroll to a section while still maintaining the functionality of Locomotive Scroll?

Here is my last attempt:

  const { scroll } = useLocomotiveScroll();

  const scrollToSection = (e) => {
    e.preventDefault();
    const targetId = e.target.getAttribute('href');
    const section = document.querySelector(`${targetId}`);

    if (targetId) {
      scroll.scrollTo(section);
    }
  };

This code is from a navigation component.

And this is the hook:

import { useLayoutEffect } from 'react';
import LocomotiveScroll from 'locomotive-scroll';
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';

const useLocoScroll = (start) => {
  gsap.registerPlugin(ScrollTrigger);

  useLayoutEffect(() => {
    if (!start) return;

    const scrollEl = document.querySelector('.App');

    let locoScroll = new LocomotiveScroll({
      el: scrollEl,
      smooth: true,
      multiplier: 1,
    });

    locoScroll.on('scroll', ScrollTrigger.update);

    ScrollTrigger.scrollerProxy(scrollEl, {
      scrollTop(value) {
        if (locoScroll) {
          return arguments.length
            ? locoScroll.scrollTo(value, 0, 0)
            : locoScroll.scroll.instance.scroll.y;
        }
        return null;
      },
      scrollLeft(value) {
        if (locoScroll) {
          return arguments.length
            ? locoScroll.scrollTo(value, 0, 0)
            : locoScroll.scroll.instance.scroll.x;
        }
        return null;
      },
      getBoundingClientRect() {
        return {
          top: 0,
          left: 0,
          width: window.innerWidth,
          height: window.innerHeight,
        };
      },
      pinType: document.querySelector('.App').style.transform
        ? 'transform'
        : 'fixed',
    });

    const lsUpdate = () => {
      if (locoScroll) {
        locoScroll.update();
      }
    };

    ScrollTrigger.addEventListener('refresh', lsUpdate);
    ScrollTrigger.refresh();

    return () => {
      if (locoScroll) {
        ScrollTrigger.removeEventListener('refresh', lsUpdate);
        locoScroll.destroy();
        locoScroll = null;
      }
    };
  }, [start]);
};

export default useLocoScroll;

Oliver
  • 177
  • 1
  • 10

0 Answers0