1

When a user clicks a link that directs the user to a new page, it generally put the user's view in the middle of the new page, at the same position as the original link. To prevent this, we can use the well-known method; scrolling up from window events.

I would like to know if there are any alternatives or tips that will prevent the user from seeing the scrolling up. Ideally, I would like the view to be at the top straight away like a new open page.

Thank you,

5
  • reactrouter.com/web/guides/scroll-restoration Commented May 4, 2021 at 11:42
  • I do not want to see the effect of scrolling to the top. I've already implemented this method. I am looking for having the same effect of a new page reached that starts at the top of the page straight away. Thank you. Commented May 4, 2021 at 12:19
  • I don't think that would be possible. window.scrollTo({top: 0}); is instant. It should be fast enough. See stackoverflow.com/a/55926067/2873538 Commented May 4, 2021 at 12:28
  • I find the experience unpleasant even if it is fast. I went to the Airbnb website to simulate a click on a link and, instead of having a scrolling up, we have a new page rendering. Having a server-side rendering, using node.js for example, might be a solution for my problem? Thank you very much for your time and answers so far. Commented May 4, 2021 at 12:47
  • You should try the SSR. That may solve the issue (if each link's page would come from server). Commented May 4, 2021 at 12:59

1 Answer 1

1

I found the following solution in my case to behave like a new page:

 const ParentComponent: React.FC = () => { const [isViewTopPage, setViewTopPage] = useState(false); const scrollToTheTop = () => { window.scrollTo({ top: 0, behavior: 'smooth' }); let result = window.scrollY === 0; setViewTopPage(result); }; useEffect(() => { // If the user refresh the page if (window.scrollY === 0) { setViewTopPage(true); } // User coming from the link clicked if (!isViewTopPage) { window.addEventListener('scroll', scrollToTheTop); } return () => window.removeEventListener('scroll', scrollToTheTop); }, [isViewTopPage]); return ( <section id="parent-component"> {/* Your conditional rendering *} {isViewTopPage && ( <Header/> <YourChildComponent/> <Footer/> )} </section> ); }; 

Note: as my child component was not too down from the top viewport, the scrolling up was very fast. It might not be the case for you if your child component is too down. You might have to implement an animation while scrolling up for the user experience.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you can use the code as shown in this example. But, replace useEffect with useLayoutEffect and it should do scroll restoration instant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.