darkroomengineering / lenis

How smooth scroll should be
https://lenis.darkroom.engineering
MIT License
9.03k stars 385 forks source link

lenis.stop() is not a function #180

Closed joebentaylor1995 closed 1 year ago

joebentaylor1995 commented 1 year ago

Describe the bug When i call lenis.stop(); i get this error:

Cannot read properties of undefined (reading 'stop')

To Reproduce call lenis.stop()

joebentaylor1995 commented 1 year ago

An example of my smoothscroll component:

// Imports
// ------------
import React from 'react';
import Lenis from '@studio-freight/lenis';
import { ScrollContext } from '@states/contexts';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { SplitText } from 'gsap/SplitText';

// Plugin Register
// ------
if (typeof window !== 'undefined') {
    gsap.registerPlugin(ScrollTrigger, SplitText);
}

// Component
// ------------
const SmoothScroll = ({ children, location }) => {
    // NOTE • Lenis smooth scrolling
    let lenis;

    // NOTE • States
    const [scrollProgress, setScrollprogress] = React.useState(0);
    const [canScroll, setCanScroll] = React.useState(true);

    // NOTE • Initialize Lenis smooth scrolling
    const initSmoothScrolling = () => {
        lenis = new Lenis({
            lerp: 0.02,
        });

        lenis.on('scroll', () => ScrollTrigger.update());

        gsap.ticker.add((time) => {
            lenis.raf(time * 1000);
        });

        //get scroll value
        lenis.on('scroll', ({ scroll, limit, velocity, direction, progress }) => {
            // console.log({ scroll, limit, velocity, direction, progress });
            setScrollprogress(scroll);
        });

        const scrollFn = (time) => {
            lenis.raf(time);
            // console.log('Lenis:', lenis);
            requestAnimationFrame(scrollFn);
        };

        requestAnimationFrame(scrollFn);
    };

    // NOTE • Activate & Destroy Lenis smooth scrolling
    React.useEffect(() => {
        initSmoothScrolling();

        return () => {
            lenis.destroy();
        };
    }, [location]);

    React.useEffect(() => {
        console.log(lenis);

        if (!canScroll) {
            lenis.stop();
        } else {
            lenis.start();
        }
    }, [canScroll]);

    return (
        <ScrollContext.Provider value={{ scrollProgress, canScroll, setCanScroll }}>
            {children}
        </ScrollContext.Provider>
    );
};

export default SmoothScroll;
joebentaylor1995 commented 1 year ago

Found that lenis.stop() needed to be called inside my first React.useEffect()l