preact-router
preact-router copied to clipboard
Scroll to top for Link
If I have two pages with scrollbar and when I'm clicking one link the scroll position remains the same on the other page.
I could scroll to top on each page render, but I want to keep my scroll position for 'back' button.
Back and Forward buttons in browser works fine now, scroll position is keeping for each page.
So I think the Link or route() function should have window.scrollTo(0, 0) on click.
Or am I missing something?
hi try with this....
handleRoute = e => {;
this.currentUrl = e.url;
window.scrollTo({ top: 0 });
};
render() {
return (
<div className="app">
<Helmet>
<title>Titulo de la pagina</title>
</Helmet>
<Header />
<div className="content">
<Router url={this.props.url} onChange={this.handleRoute}>
{routes.map(({ path, component: C }) => (
<C path={path} key={path} />
))}
</Router>
</div>
<Footer />
</div>
);
}
This was intentionally left out of the library by default, because it's hard determine when it would be appropriate to scroll to the top of the page (eg: should we do this for programmatic navigation? what about history back/forward?)
Here's a "polyfill":
let old = history.pushState;
history.pushState = function() {
old.apply(this, arguments);
scrollTo(0, 0);
}
I would expect a scroll to happen if clicking a link or calling route, but not if navigating by history or using a fragment in the link.
Is there a path to do this without modifying globals?
@developit It would be nice to be able to keep the browser default on maintaining/resetting scroll position. The current approach seems pretty broken for common scenarios (e.g. click link > go to another page). Most browsers I am aware of reset the scroll position when the user clicks a link but remember the scroll position with history navigation (forward & back buttons).