Reputation: 51
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,
Upvotes: 1
Views: 417
Reputation: 51
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.
Upvotes: 1