darkroomengineering / lenis

How smooth scroll should be

Home Page:https://lenis.darkroom.engineering

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReactLenis: unable to scrollTo on route change

maurotenti-dentsu opened this issue · comments

Hey there, first off thank you for this awesome library. It is the default for my every new project.

At the moment I'm using it in a Next.js (14.1.0) app that still uses the pages router, via ReactLenis.

Describe the bug
I'm trying to trigger the scrollTo function of the Lenis instance provided with useLenis on page mount (using an effect), but the function is not firing.
I logged lenis and the function itself and they are both defined.
ReactLenis is rendered in a Layout component common for every page and I noticed that remounting the Layout on every route change "solves" the issue and the page scrolls as expected. Also, adding a small delay to the scroll after the page is mounted makes the function fire correctly.

To Reproduce
I made a sandbox
that uses React Router Dom (v5) since the behaviour is the exact same as with Next.js.

Thank you for your support.

https://codesandbox.io/p/sandbox/competent-water-t7f36k?file=%2Fsrc%2FApp.tsx%3A14%2C69

add key to your pages, otherwise React consider it's the same component

Thank you for your quick reply!
I'm sorry to bother but in the sandbox you shared I would expect the scrolling to happen even when navigating from the "homepage" and one the other two pages since the effect is running. At the moment is happening only when I switch between "page" and "page (scroll delayed)". Am I missing something silly?

I'm sorry but that's a React issue unrelated with Lenis, I guess you should find the solution somewhere else.

Your hook is located in Page, in '/' you never call Page.

FYI I kind of solved the issue by calling the resize method before scrollTo. This also explains why delaying the scrollTo by more than 250ms (since it is called automatically by Lenis after that amount of time) works.

https://codesandbox.io/p/sandbox/throbbing-butterfly-69387c

There's no problem. To me the solution I found is fine. Maybe it could help someone else in the future. It could be bound to the ResizeObserver API and React messing with the DOM, but at the moment I do not need to explore it deeper

your exemple works even without the lenis.resize()

I'm sorry but it seems that my example wasn't clear. When navigating from "homepage" to "page-1" the Page components mounts and I would like it to scroll down as soon as the page renders. Without the resize this doesn't happen. But when I add it it does