I have a react application and I am struggling to remove the previous page scroll-position
.
Please I would appreciate it if you understand my problem before concluding.
I do not want to preserve the scroll history
. I want it to always go back to the top of the page.
I have used the solution below to make the application scroll back to the top of the page whenever a user navigates to a new page.
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const ScrollToTop = ({ children }) => {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return children || null;
};
export default ScrollToTop;
The above code is working very fine with no issues. What is not working for me is:
When a user clicks a Button
I created using Link
from react-router-dom
they are navigated to the new page (correct page), but the scroll-position
is of the previous page (the page they are coming from).
I have tried using these hooks.
useLayoutEffect
withRouter
(is removed from react-router v6)useHistory
(is removed from react-router v6useNavigate
They are not working.
How can I resolve this? Or is there something I am missing?
I have also tried implementing the solution below. But wont work.
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
CodePudding user response:
You can scroll to Top every time the user enters that screen, with focus hook https://reactnavigation.org/docs/function-after-focusing-screen/.
CodePudding user response:
After 4 hours of research and trying and errors. I have found the solution to this.
In react-router
v6. You do not need to your window. on your useEffect
You just need to have your code like this:
useEffect(() => {
document.body.scrollTo(0, 0);
});
I found the answer here, and researched more on it.