React App Smooth Scroll With “react-scroll”
I am going to show you how you can achieve smooth scrolling in a very simple and fast way with the “react-scroll” package. This is especially useful when creating landing pages and trying to implement smooth scroll interactions. There is more to “react-scroll” than I will be showing so be sure to check out the docs to get the full scope of it.
First, as always we need to install the package
npm install react-scroll *OR* yarn add react-scroll
For a typical home page we can probably assume there will be a home, about, and contact section, so let’s build them out.
Create a component for each section, as well as a nav bar and render them within your App.js file.
Nav.js
We are going to import Link from ‘react-scroll” and each Nav item will be a Link within a li tag.
- activeClass = “active” is used for the styling applied to the active nav bar item that the user is currently on, more on that in a little.
- to is going to be the destination of the link, this will correspond to the id of the sections I will show next.
- spy is going to allow the nav bar items to become active if the user is scrolling over the corresponding section.
- smooth allows a smooth scroll transition when clicking to a section.
- offset is basically the padding px when it scrolls to a section, you can play with this for personal use.
- duration is the time it takes for the scroll to travel to your clicked section. {1000} would be one second.
Components
About.js
I used section here but you can also use a div. The important part is setting the id of your container to whatever you set each “Link to” when creating the nav bar. Follow the same convention for all your components.
Thats it! When you click on a nav item it should take you to the corresponding section with a smooth scroll. One last think I will show you is the “active” class that comes from “react-scroll”
In your css file, add this class for styling the nav item that is currently being visited. This will help show users where they are on your landing page and is a pretty nice touch to add.