DEV Community

Areeb ur Rub
Areeb ur Rub

Posted on

Highlight Nav-Link on scroll through Section, in React JS;

Buy Me A Coffee

Recently I posted about Nav-link's to active as you scroll in my series 10 Lines of JavaScript.

Now, I will tell you how you can do the same in your React websites.

So for this we need to install a package typically named react-scrollspy-highlight so first we need to install this package

Install Package



npm i react-scrollspy


Enter fullscreen mode Exit fullscreen mode

Using it in your project,

first import the library like this


 Scrollspy from 'react-scrollspy'

Enter fullscreen mode Exit fullscreen mode

Then give each section on your page different id and link them to the nav-links

and then use the library like this:



  <Scrollspy
        items={ ['section-1', 'section-2', 'section-3'] }
        currentClassName="active" >

    <li><a href="#section-1">section 1</a></li>
    <li><a href="#section-2">section 2</a></li>
    <li><a href="#section-3">section 3</a></li>

  </Scrollspy>


Enter fullscreen mode Exit fullscreen mode

mention the id's of Section in form of array in the prop items.

After adding this, create styling for className active, the class under currentClassName will be added to section's classList as scroll reach on the section.

in case you don't know : Those { [...] } curly brackets around the array in prop item is just a way to mention javascript in JSX, this not mean items store an object.

One more tip for smooth scroll,

Some people get trouble with smooth scrolling and use different libraries to do so but there is a simple css property which will enable smooth-scroll, scroll-behavior:smooth; add this to body or html and then the scroll on the page will be smooth.



html,body {
  user-select:none;
}


Enter fullscreen mode Exit fullscreen mode

for more: visit react-scrollspy-highlight

Buy Me A Coffee

Read Also:

Follow for more:

Top comments (0)