I have tried everything i found on stackOverflow and Github community but i still can not find a way to scroll the page to the top when it renders. In my last effor i added a ScrollTop component
import { useEffect } from "react";
import { withRouter } from "react-router-dom";
const ScrollToTop = ({ children, location: { pathname } }) => {
useEffect(() => {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth",
});
}, [pathname]);
return children || null;
};
export default withRouter(ScrollToTop);
and i added it to the index.js file
import ScrollToTop from "./components/ScrollTop";
ReactDOM.render(
<BrowserRouter>
<ScrollToTop>
<App />
</ScrollToTop>
</BrowserRouter>,
document.getElementById("root")
);
Can anyone explain to me why this isn't working?
I also tried the useEffect in each component i want to render with the window.scrollTo(0,0) but it didn't work.
question from:
https://stackoverflow.com/questions/65830209/why-scroll-the-page-to-the-top-does-not-work-in-react 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…