Forem

Areeb ur Rub
Areeb ur Rub

Posted on

7 1

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:

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay