Recently I posted about Nav-link's to active as you scroll
in my series 10 Lines of JavaScript.
Nav-link's to active as you scroll through sections, in 10 Lines of JavaScript;
Areeb ur Rub ・ Jun 8 '21
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
Using it in your project,
first import the library like this
Scrollspy from 'react-scrollspy'
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>
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;
}
for more: visit react-scrollspy-highlight
Read Also:
Hide NavBar as Scroll down, in less than 10 lines of javascript;
Areeb ur Rub ・ May 24 '21
#javascript #tutorial #webdev #cssFollow for more:
Top comments (0)