Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

javascript - Why Scroll the page to the top does not work in react?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...