简体   繁体   中英

Smooth scrolling when clicking an anchor link on react/next.js

Is it possible using only CSS to make smooth scrolling when clicking an anchor link in react component?

...
render(
    <a href="#smooth-link">Link To There</a>
    ....
    <div id="smooth-link">
        ....
    </div>
)

There's this:

/**
 * Smooth scrolling inside an element
 */
#my-element {
    scroll-behavior: smooth;
}

/**
 * Smooth scrolling on the whole document
 */
html {
    scroll-behavior: smooth;
}

Source

But I feel like JS does a better job:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

So you could give that a try: docs

use npm i react-scroll package

You have to add click listener on anchor tag inside of <Link> tag:

 <Link href="#about">
     <a className="nav-item" onClick={scrollHandle} id="about-">About Us</a>
 </Link>

scrollHandler:-

 const scrollHandle = (e) => {
  e.preventDefault();
  let id = e.target.id;
  let position = document.getElementById(id.slice(0, id.length - 1)); //removing extra last - (dash)
  window.location.href = "#" + id.slice(0, id.length - 1); // changing the url
  position && position.scrollIntoView({ behavior: "smooth", block: "start" }) //scrolling the page
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM