Callum Kloos
Callum Kloos

Reputation: 13

Force <Link> component to scroll to top of layout in next.js 13

I have a dynamic route in the app router, with a shared parent layout. I have some <Links> that are dynamically populated within the page, and the desired behaviour would be that when the links are clicked, scroll is reset to the top of the page. The default behaviour however seems to retain the current scroll position.

Here is the file structure:

layout.tsx
[slug] / page.tsx

In each page.tsx I have a related posts component, and this component houses the <Links> to other slugs in the route. Another answer during the beta suggested adding a useEffect on the layout, however forcing the layout into a client component seems like overkill for this simple functionality.

Thanks in advance for the advice.

Upvotes: 1

Views: 3349

Answers (1)

tem
tem

Reputation: 157

The <Link> component is not the cause of your issue. By default it opens the URL specified as its href prop at the scroll position (0,0) that is at the top-most of the web page. This is behavior is specified by the attribute scroll which is true by default (See the Doc here).

Your problem probably comes from the styles defined by default in src/styles/globals.scss (if you're using sass) src/styles/globals.css (otherwise) . Check if one of the following style rules (overflow, overflow-x, overflow-y, scroll-behavior) is defined either on the html or body selector then remove it.

Upvotes: 0

Related Questions