Search code examples
javascripthtmlcssreactjsscroll

How to fix webpages scrolling down


I have a React project with 3 components (for separate web pages). If I scroll the landing page and then change to other pages, I can see other pages are showing from that scrolled-down position. I have to scroll up to see the page top. How to fix that? Every component has the same parent component .

import React from "react";
import Header from "./Header";
import Footer from "./Footer";

    function Layout({ children }) {
      return (
        <div>
          <Header />
          {children}
          <Footer />
        </div>
      );
    }

export default Layout;


function Artists() {
 <Layout>
   <div>
    <h2>ARTIST</h2>
   </div> 
</Layout>
}

these children are pages. I tried to give individual scroll bars to each page, then 2 scrollbars appeared one from the body and one from the page. If I am adding overflow: hidden to the body, then other scroll options are not working. Is there any simple way to fix this issue?


Solution

  • i have not test your code but it seems like the browser retaining the scroll position as you navigate between pages an don't reset it because it doesn't consider the page in question but only the change of component represent by childreen inside you layout component it's as if for your browser you're always on the same page, you can solve this by resetting yourself the scroll each time your page loads, even though I don't consider this a good practice.you can reset it inside a useEffect like this

    function Artists() {
       useEffect(() => {
          window.scrollTo(0, 0);
        }, []);
       <Layout>
         <div>
          <h2>ARTIST</h2>
         </div> 
      </Layout>
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>