Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading