Use npm ‘react-scroll’ in React

Suppose that we have built a navbar in React using pure CSS, the next step is to make it more functional. For example, we have four links in the navbar (‘Home’, ‘About’, ‘Projects’, and ‘Contact’) for a personal portfolio website. When we click one of them, the page should be scrolled down to the specific part on the main page.

In the pure HTML, things are quite simple to achieve our goal:

<a href= “#content1” >Content1</a>

<div id= “content1”>…</div>

However, in React, we use components, which makes it quite confusing to put the anchor tag combined with its corresponding contents.

During my research, I found an npm package named ‘react-scroll’ which solves my problem.

Install

$ npm install react-scroll

Following is how I use it in my code:

import { Link } from “react-scroll”;

Navbar.js

Replace each anchor tag with <Link> tag that imports from ‘react-scroll’.

<Link activeClass="active"
to="target"
spy={true}
smooth={true}
hashSpy={true}
offset={50}
duration={500}
delay={1000}
isDynamic={true}
onSetActive={this.handleSetActive}
onSetInactive={this.handleSetInactive}
ignoreCancelEvents={false}
>
Your name
</Link>

Then, in the App.js:

App.js

In App.js, we use the <Element> tag to wrap our components.

That’s it!

More info about this npm package can be found here.