'How to correctly use Locomotive Scroll with Next.js routing?
I'm using locomotive-scroll with Next.js and all working fine. But after route to a different page, my scroll won't destroy and 2 scrolls overlap each other.
How to correctly reinit locomotive-scroll in Next.js after route?
My code example:
function MyApp({ Component, pageProps }) {
useEffect(() => {
import("locomotive-scroll").then((locomotiveModule) => {
let scroll = new locomotiveModule.default({
el: document.querySelector("[data-scroll-container]"),
smooth: true,
smoothMobile: false,
resetNativeScroll: true,
});
scroll.destroy(); //<-- DOESN'T WORK OR IDK
setTimeout(function () {
scroll.init();
}, 400);
});
});
return (
<main data-scroll-container>
<Component {...pageProps} />
</main>
);
}
Solution 1:[1]
everything @juliomalves said is true. but i just wanted to add one point. Locomotive works by initialising itself and reading the actual document size on page load. but the situation with next js routing is that the page loads only once, after that its only components changes, no actual page reloading. so the Scroll instance will assume the page is still the same size on load. this leads to a lot of bugs and page breakage.
the way i solved it is by adding this line at the app component:
useEffect(()=> window.dispatchEvent(new Event('resize')), [Component])
this way the resize event will trigger every time the page "component" is switched. the locomotive Scroll instance will pick up this event and recalculate the page size according to the new component size.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Moe Ibrahim |
