Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth scroll in next js

How can I set the scroll effect to smooth (globally) in Next.js? I tried to do it on the global css, but it deactivates the scroll-to-top that Next js already has.

I tried this solution that i found on internet too, but it didn't worked either.

 componentDidMount() {
 Router.events.on('routeChangeComplete', () => {
    window.scroll({
       top: 0,
       left: 0,
       behavior: 'smooth'
    });
 });

}

like image 414
Manuel Nelson Avatar asked Dec 05 '25 04:12

Manuel Nelson


2 Answers

Add scroll-behavior:smooth in html or body. Then adding in

<Link href="#someid" scroll={false}>

works

like image 186
Shubham Gaikwad Avatar answered Dec 07 '25 20:12

Shubham Gaikwad


Just put style={{scrollBehavior:'smooth'}} in the tag Html in '_document.tsx' file.

Like :

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html className='scroll-smooth' style={{scrollBehavior:'smooth'}}>
        <Head>
          <link rel='icon' href='/favicon.ico' />
          <meta
            name='description'
            content='A place to find a great film to watch'
          />
        </Head>
        <body className='bg-gray-50 screen'>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
like image 39
Charles-Lévi BRIANI Avatar answered Dec 07 '25 18:12

Charles-Lévi BRIANI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!