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

yotube
0

Issue

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>
)

Solution

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



Answered By - geertjanknapen

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top