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
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';
to:
import { Link } from 'react-scroll';
(Before we move on, we need to make sure that we have id
s 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>
To quickly break that down:
- We are linking
to
ourid
- 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
totrue
(which makes Link selected when scroll is at its targets position) - We set
smooth
totrue
(which sets the animation) - The
offset
makes up for any additional pixels that need to be scrolled due to padding or something, and theduration
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.
Top comments (1)
I really like the explanation, but I can't make it work if the link is in another page
I want to scroll into contact in the main page, and if I'm in another one it doesn´t work
I thought using
/#contact
will work but no