I'm going crazy, I'm using react-router-dom, the moment I go from page A to B I want it to start at the top of the page, everywhere. I've tried different things like:
componentDidUpdate(){
console.log('hello');
document.documentElement.scrollTo(0, 0)
}
&
componentDidUpdate(){
console.log('hello');
window.scrollTo(0, 0)
}
&
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return() => {
unlist();
}
}, []);
return(null);
}
export default withRouter(ScrollToTop);
But unfortunately without success, is there anyone who can tell me what I can do? I'm using :react": "^16.14.0"
So the intention is if I click on a <Link to={'../shopping cart'}>Shopping cart</Link>
I will end up at the top of the page!
CodePudding user response:
maybe you can use useRef hook. something like this:
const linkRef = useRef(null);
useEffect(() => {
if (linkRef.current) {
linkRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, []);
return <Link ref={linkRef} to='/shopping-card' />
CodePudding user response:
You can take a look at: https://v5.reactrouter.com/web/guides/scroll-restoration/scroll-to-top
And maybe check is your scroll container window?