I have a React page with buttons at the top in the header.
What I want is to be able to make the page auto-scroll smoothly to a specific location of the react page when clicking on one of the buttons in the header.
I have a React page with buttons at the top in the header.
What I want is to be able to make the page auto-scroll smoothly to a specific location of the react page when clicking on one of the buttons in the header.
I used <button onClick={()=> window.location.replace('/#info')}>Info</button>
to get to <h2 id='info'>ABOUT ME</h2>
.
The result was that the page did go to the location, but it didn’t scroll or smooth-scroll to the area.
0
You can use a combination of href and CSS to achieve this.
CSS
html {
scroll-behavior: smooth;
}
React
<a link="#section"></a>
Should be enough. If you want to use JS, you can use scrollIntoView but since you are using React, it won’t be recommended.
Follow this thread for more information
You can achieve this by using HashRouter from react router dom along with tweenjs for animation, here is an example:
HashRouter v5 with tweenJs
const animateScrolling = useCallback(
(name) => {
const coords = { y: window.scrollY || window.pageYOffset },
target = document.getElementById(name.replace('/', ''));
if (target) {
// Create a new tween that modifies 'coords'.
tweenRef.current = new Tween(coords)
// Move to top of the clicked element in 700ms.
.to({ y: elementOffsetTop(target).top + 10 }, scrollDuration)
// Use an easing function to make the animation smooth.
.easing(Easing.Quadratic.Out)
.onUpdate(function () {
// Called after tween.js updates 'coords'.
// Move 'box' to the position described by 'coords' with a CSS translation.
window.scrollTo(0, coords.y);
})
// Start the tween immediately.
.start();
requestAnimationFrame(animate);
}
},
[animate, elementOffsetTop]
);
In this example I’m using react router dom v5 , if you would prefer to use react router dom v6, have a look at this repository:
HashRouter v6 with tweenJs