DEV Community

loading...
Cover image for Implementing Smooth Scroll

Implementing Smooth Scroll

Max Zander
Professional Opera Singer turned Full-Stack Developer
・2 min read

When I initially built the site for Adrian’s Dream, I used react-router-dom to set my routes for each individual page. As I was designing and building though, I realized that what I really wanted was to have everything on a single page and, rather than having the navbar redirect us to a different page, I wanted it to scroll to the clicked component.

 So in this post, I am going to tell you about react-scroll and how to use it.


To get started, run:

npm install react-scroll --save
Enter fullscreen mode Exit fullscreen mode

to add react-scroll to your package.




Now we jump to our navbar component and we change our Link import from:

import { Link } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

to:

import { Link } from 'react-scroll';
Enter fullscreen mode Exit fullscreen mode

(Before we move on, we need to make sure that we have ids for each of the places on the page that we want to scroll to. So if you don't have those yet, go ahead and add those.)

Now for the fun part! We're going to actually implement the functionality. Back in our navbar component, we are going to change what's in our Link tag so that each one looks as follows:

   <li className='nav-item'>
       <Link
       to='about'
       className='nav-links'
       onClick={closeMobileMenu}
       spy={true}
       smooth={true}
       offset={-70}
       duration={500}>
           ABOUT
       </Link>
  </li>
Enter fullscreen mode Exit fullscreen mode

To quickly break that down:

  • We are linking to our id
  • We have our className
  • We set our onClick to close the menu when it is in mobile view (no applicable for desktop view)
  • We set spy to true (which makes Link selected when scroll is at its targets position)
  • We set smooth to true (which sets the animation)
  • The offset makes up for any additional pixels that need to be scrolled due to padding or something, and the duration is how long (in milliseconds) it is going to take.

And honestly, that's it! Set that for each nav-item and you've got yourself a smooth-scrolling page!

Please check out Adrian’s Dream for any of your crafting needs! It's a wonderful company with a meaningful story.

Discussion (0)