applying duration with smooth scroll

Viewed 420

I am using react-router-hash-link instead of React-Scroll because I needed to link to another component as well as applying smooth scrolling. I am able to do an offest to the scroll but I do not know how add duration to the scroll. How do I add duration to the scroll? Many thanks in advance and greatly appreciate any help. Here is my code:

const scrollWidthOffset = (el) => {
    const yCoordinate = el.getBoundingClientRect().top + window.pageYOffset;
    const yOffset = -80; 
    window.scrollTo({ top: yCoordinate + yOffset, behavior: 'smooth' }); 
}



<div className="collapse navbar-collapse" id="navbarCollapse">
  <div className="navbar-nav ml-auto">
     <Link activeClass="active" smooth to="/#intro" scroll={el => scrollWidthOffset(el, -100)} className="nav-item nav-link">Home</Link>
     <Link activeClass="active" smooth to="/#about" scroll={el => scrollWidthOffset(el, -80)} className="nav-item nav-link">About Us</Link>
     <Link activeClass="active" smooth to="/#contact"  scroll={el => scrollWidthOffset(el, -80)} className="nav-item nav-link">Contact</Link>
     <Link activeClass="active" to="/login#loginform" className="nav-item nav-link">Login</Link>
  </div>
</div>
1 Answers

I had the exact same issue, I wanted smooth scrolling to anchor tags. I have managed to do it, it might not be the prettiest but it should get it done. It combines both hash link and react-scroll:

You will need to install the below dependancies, codes below to copy and paste:

npm i --save react-anchor-link-smooth-scroll
npm i --save react-scroll
npm i --save react-router-hash-link

Then this code should go in your Navbar file on each link, I've used your #intro for example:

 <Link
     activeClass="active"
            to="/#intro"
            spy={true}
            smooth={true}
            offset={-70}
            duration={5000}
       >
       <Nav.Link id="nav-links" href="/#intro">
            Services
       </Nav.Link>
 </Link>

Then finally, wherever you want to scroll to, put the id in the html like below

<div id="intro">This is the Intro</div>

I hope this helps in some way!

I followed the two below guides and put them together....

This to get the anchor tags to work... and this to get the smooth scrolling

Related