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:
JavaScript
x
25
25
1
function MyApp({ Component, pageProps }) {
2
useEffect(() => {
3
import("locomotive-scroll").then((locomotiveModule) => {
4
let scroll = new locomotiveModule.default({
5
el: document.querySelector("[data-scroll-container]"),
6
smooth: true,
7
smoothMobile: false,
8
resetNativeScroll: true,
9
});
10
11
scroll.destroy(); //<-- DOESN'T WORK OR IDK
12
13
setTimeout(function () {
14
scroll.init();
15
}, 400);
16
});
17
});
18
19
return (
20
<main data-scroll-container>
21
<Component {pageProps} />
22
</main>
23
);
24
}
25
Advertisement
Answer
You should move the scroll.destroy
call to the cleanup phase of the useEffect
. You also don’t need to explicitly call scroll.init()
.
JavaScript
1
27
27
1
function MyApp({ Component, pageProps }) {
2
useEffect(() => {
3
let scroll;
4
import("locomotive-scroll").then((locomotiveModule) => {
5
scroll = new locomotiveModule.default({
6
el: document.querySelector("[data-scroll-container]"),
7
smooth: true,
8
smoothMobile: false,
9
resetNativeScroll: true
10
});
11
});
12
13
// `useEffect`'s cleanup phase
14
return () => {
15
if (scroll) scroll.destroy();
16
}
17
});
18
19
return (
20
<main className="main" data-scroll-container>
21
<Layout>
22
<Component {pageProps} />
23
</Layout>
24
</main>
25
);
26
}
27