Smooth Page Scroll

From https://hackernoon.com

If you are a front-end developer, you may want to be able to provide a high-quality front-end user experience, such as when the user clicks a button and triggers a smooth page scroll, and such tiny details can improve your user experience. Recently, I found a convenient tool to help you. React-scroll can easily add a page scrolling effect to your website or web app, and it brings various scrolling effects.

Let’s dive into it. First, you need to install the package to your project.

Open your terminal and type npm install react-scroll, hit ENTER. And it should take a few seconds to load.

npm install react-scroll

I create a few pages to demonstrate the page scrolling effect. And here is the code from the home page, and the rest of the pages follows the same pattern.

In your App.js, import all the pages you just created.

And, Now we gonna focus on the Navbar.

The traditional way to achieve the smooth page scrolling effect is to use internal links: add an id to every page like:

HTML:

<section id=“home”></section>

HTML code in navbar

<a href=“#home”></a>

CSS:

html{

scroll-behavior: smooth;

}

Of course, you can add jQuery to get the same result. But you will type lots of code, we want to make this simple.

It seems there are lots of things going on in the navbar section. I will break it down into little pieces and go through every one of them with you.

We need to import Link from react-scroll, be careful do not to import from “react-router-dom”!

import { Link } from “react-scroll”

  1. activeClass=“active” which automatically adds a class name “active” or you can use any other name, it is completely up to you. With a new class name added to the nav, you can style the link and make it stand out which indicates which page is browsing by the user.
  2. to ={page}, or you can type to= “home”. Because I pass the name to the function scrollLink. to keep my code DRY.
  3. spy = {true} This enable the ability to make Link selected when the scroll is at its targets position.
  4. smooth={true} this is will turn the smooth scroll on. And this is exactly what we need to make our website scroll smoothly.
  5. duration ={500} this is where you can control the speed of the smooth scroll.

The most important thing is to have more practice, be familiar with these packages, and add them to your own inventory.

If you want to learn and discover more secret trick about react scroll: you can go to https://www.npmjs.com/package/react-scroll

Here is the demo below 👇:

please feel free to try it on yourself.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
ZHENGJIAN LIU

ZHENGJIAN LIU

Software engineer experienced in Ruby on Rails, React, and Javascript based programming. zhengjianliu.com