Home > other >  My React app page scroll to Top is ugly. Is there a scroll method that doesn't scroll?
My React app page scroll to Top is ugly. Is there a scroll method that doesn't scroll?

Time:11-09

I understand react is a single page app. Is there a scroll method that doesn't scroll the page and is on the top by default? Or what tricks can be used to do that?

  useEffect(()=>{ 
    window.scrollTo(0,0);
       // eslint-disable-next-line react-hooks/exhaustive-deps  
  },[])

More clear :

I visit a page and scroll to bottom. When I go to other page using Link, the visited page scrolled from bottom to top (animated scrolled).

I hope the visited page is on the top by default. Not animated scrolled.

CodePudding user response:

The scrollTo function accepts an object with options as well. This way, you can explicitly set the behavior to instant.

Also, you should use the useLayoutEffect hook to avoid any flickering after the initial render.

Please refer to the official documentation: https://reactjs.org/docs/hooks-reference.html#uselayouteffect

import { useLayoutEffect } from 'react';    

export default Page = (props) => {
    useLayoutEffect(() => {
        window.scrollTo({
            left: 0,
            top: 0,
            behavior: 'instant',
        });
    }, []);

    return (
        <div>Hello World!</div>
    );
};
  • Related