Next.js: Add option to Link to make scrolling to '#' id smooth

Created on 10 Sep 2018  路  11Comments  路  Source: vercel/next.js

Feature request

Is your feature request related to a problem? Please describe.

I'd like to use smooth scrolling, when using a Link like <Link href='/mypage#section3'>mylink</Link>

Describe the solution you'd like

Adding an option like <Link href='/mypage#section3' scrollSmooth>mylink</Link> or any other method to make this behaviour work.

Describe alternatives you've considered

Not using '#', but only javascripts elem.scrollIntoView(...)

Additional context

None

Most helpful comment

In global styles add

scroll-behavior: smooth; for html tag

like this :

<style global jsx>
   {`
       html {
          scroll-behavior: smooth;
        }
  `}

All 11 comments

You can use an external library.
Why they should have to implement a feature which not necessary to all users?
You can scroll to hash of the URI in the componentDidMount of the App component.

@giovannigiordano Problem is that nextjs will automatically scroll to the hash instantly (see here). Smooth scrolling takes much longer and so if I try to smooth scroll in componentDidMount than the router has already scrolled to that element "unsmooth".

@olastor you can use any other attribute besides the ID to target the anchor on componentDidMount, so you prevent the browser default behavior. Another solution is to add a prefix in your anchor ID, so the anchor's ID would be {prefix}-{hash}.

@giovannigiordano Thanks for the ideas. Will try that.

@giovannigiordano @olastor so how can i know the hash changed? I tried to listen to the hashchange, but it don't work when i click the Link.

any solution?

In global styles add

scroll-behavior: smooth; for html tag

like this :

<style global jsx>
   {`
       html {
          scroll-behavior: smooth;
        }
  `}

Any solution yet?

In global styles add

scroll-behavior: smooth; for html tag

like this :

<style global jsx>
   {`
       html {
          scroll-behavior: smooth;
        }
  `}

While this may work, the support is for it is very limited. I would not suggest this to use in a production application/website. https://caniuse.com/?search=scroll-behavior

Same prolem... but the scroll-behavior: smooth on the global styles works! Someone knows how to control the animation time or ease options?

In global styles add

scroll-behavior: smooth; for html tag

like this :

<style global jsx>
   {`
       html {
          scroll-behavior: smooth;
        }
  `}

Thanks man!!! Works!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Timer picture Timer  路  90Comments

arunoda picture arunoda  路  103Comments

poyiding picture poyiding  路  73Comments

robinvdvleuten picture robinvdvleuten  路  74Comments

tomaswitek picture tomaswitek  路  73Comments