I’m working on react website and I have a problem while navigating to any page that when I scroll to a certain point in a home page for example then I try to navigate to another page I find the other page is rendered from the the bottom of the page not the top
routes.tsx file
const App: React.FC = () => ( <BrowserRouter> <Layout className="layout"> <div style={{ marginBottom: "64px" }}> <Header> <AppHeader /> </Header> </div> <Content> <div className="site-layout-content"> <Routes> <Route path="/" element={<Home />} /> <Route path="/offers" element={<Login />} /> <Route path="/aboutUs" element={<AboutUs />} /> <Route path="/contactUs" element={<ContactUs />} /> <Route path="/placeDetails/:id" element={<PlaceDetails />} /> <Route path="/advantages" element={<Advantages />} /> </Routes> </div> </Content> <Footer style={{ textAlign: "center" }}> <AppFooter /> </Footer> </Layout> </BrowserRouter> ); export default App;
header.tsx
const Index = () => { const navigate = useNavigate(); return ( <Row className="header"> <Col span={12} className="header__logo"> <div className="header__logo--imgContainer" onClick={() => navigate("/")}> <img src={logoImg} alt="logo" /> </div> </Col> <Col span={12} className="header__menu"> <ul className="ant-menu-overflow ant-menu ant-menu-root ant-menu-horizontal ant-menu-light ant-menu-rtl"> <li className="ant-menu-item"> <span onClick={() => navigate("/offers")}>{strings.header.offers}</span> </li> <li className="ant-menu-item"> <span onClick={() => navigate("/advantages")}>{strings.header.services}</span> </li> </ul> </Col> </Row> ); }; export default Index;
Advertisement
Answer
you can simply use this helper component for this use case:
import { useEffect } from "react"; import { useLocation } from "react-router-dom"; export default function ScrollToTop() { const { pathname } = useLocation(); useEffect(() => { // "document.documentElement.scrollTo" is the magic for React Router Dom v6 document.documentElement.scrollTo({ top: 0, left: 0, behavior: "instant", // Optional if you want to skip the scrolling animation }); }, [pathname]); return null; }
and then you can change above code like this:
const App: React.FC = () => ( <BrowserRouter> <ScrollToTop/> // this is new helper component <Layout className="layout"> <div style={{ marginBottom: "64px" }}> <Header> <AppHeader /> </Header> </div> <Content> <div className="site-layout-content"> <Routes> <Route path="/" element={<Home />} /> <Route path="/offers" element={<Login />} /> <Route path="/aboutUs" element={<AboutUs />} /> <Route path="/contactUs" element={<ContactUs />} /> <Route path="/placeDetails/:id" element={<PlaceDetails />} /> <Route path="/advantages" element={<Advantages />} /> </Routes> </div> </Content> <Footer style={{ textAlign: "center" }}> <AppFooter /> </Footer> </Layout> </BrowserRouter> ); export default App;
This will reset the scroll position on top whenever route changes.