#Smooth scrolling in NextJS app router

5 messages · Page 1 of 1 (latest)

strange rover
#

Did anyone have a problem with scroll-behavior:smooth in nextJS app (I'm using app router)? I've been using react-ui-scrollspy and I've tried to set smooth scrolling with css and custom function that uses window.scrollTo, but nothing seems to work, while in React apps where I used the same setup it works with no problem at all. I've been stuck on this problem for a few days now, tried every fix I could find on Google and stackOverflow, so if anyone has any advice on how to make it work, I would gratly appreciate it.

tawny shell
#

First of all, NextJS (app router) renders server-side, so certain client-side features won't be available.

in other to make your component a client component, you should inlcude 'use client' keyword at the top of the file.

azure flume
#

I got it to work with next.js. I’ll get you a solution once I am near my laptop.

azure flume
#

@strange rover what worked for me (next.js v12) is the following:

  1. Define scroll-behavior: smooth; on the body tag. I used our global css file not jsx style as for some reason that did not work consistently
  2. I used Link from next.js and defined scroll behaviour as false:
<Link href={`#${VERIFICATION_STATUS_ID}`} scroll={false}>`

If I remember correctly, I tried to use native anchor tag but that did not work consistently neither.

Now I don't see any problem why this wouldn't work with server side components but if you prefer programitic approach then you should follow Victor's advice and define certain components as client side components to gain the benefit of the client side features.

strange rover