
In this article, I am going to show how to scroll the page smoothly using react-router-hash-link
How to Scroll page smoothly using react-router-hash-link in ReactJs?react-router-hash-link example. Smooth Scroll without page refreshing
When you click on a link created with react-router-hash-link it will scroll to the element on the page with the id that matches the #hash-fragment in the link. This will also work for elements that are created after an asynchronous data load. Note that you must use React Router’s BrowserRouter for this to work.
Create React Project using
- npx create-react-app my-app
- cd my-app
- npm i react-router-hash-link
Navbar.js
import React, { useState } from "react";
// import { NavLink } from "react-router-dom";
import "./NavBar.css";
import {NavHashLink as Link} from 'react-router-hash-link'
function NavBar() {
const [click, setClick] = useState(false);
const handleClick = () => setClick(!click);
return (
<>
<nav className="navbar">
<div className="nav-container">
<Link exact to="/" className="nav-logo">
GoDigital
<i className="fas fa-code"></i>
</Link>
<ul className={click ? "nav-menu active" : "nav-menu"}>
<li className="nav-item">
<Link
exact
to="/#"
activeClassName="active"
className="nav-links"
onClick={handleClick}
>
Home
</Link>
</li>
<li className="nav-item">
<Link
exact
to="/#about"
activeClassName="active"
className="nav-links"
onClick={handleClick}
>
About
</Link>
</li>
<li className="nav-item">
<Link
exact
to="/#pricing"
activeClassName="active"
className="nav-links"
onClick={handleClick}
>
Pricing
</Link>
</li>
<li className="nav-item">
<Link
exact
to="/#Service"
activeClassName="active"
className="nav-links"
onClick={handleClick}
>
Service
</Link>
</li>
<li className="nav-item">
<Link
exact
to="/#contact"
activeClassName="active"
className="nav-links"
onClick={handleClick}
>
Contact Us
</Link>
</li>
</ul>
<div className="nav-icon" onClick={handleClick}>
<i className={click ? "fas fa-times" : "fas fa-bars"}></i>
</div>
</div>
</nav>
</>
);
}
export default NavBar;
All Link pages must be defined id
Sample Page as about.js
about.js
import React from "react";
import web from '../../images/about.svg'
export const About = () => {
return (
<div>
<section id="about" className="about">
<div className="container my-4">
<content……>
</div>
</section>
</div>
);
};
export default About
More details go to the official link
Excellent pieces. Keep writing such kind of info on your blog.
Im really impressed by your blog.
Hi there, You’ve done a great job. I will definitely digg
it and for my part recommend to my friends. I’m sure they will be benefited from this website.