preact-router icon indicating copy to clipboard operation
preact-router copied to clipboard

Scroll to top for Link

Open LexRiver opened this issue 6 years ago • 4 comments
trafficstars

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?

LexRiver avatar Jun 04 '19 13:06 LexRiver

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>
		);
	}

aguilera51284 avatar Sep 20 '19 15:09 aguilera51284

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);
}

developit avatar Oct 18 '19 17:10 developit

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?

vpzomtrrfrt avatar Oct 14 '20 20:10 vpzomtrrfrt

@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).

tysonmatanich avatar Feb 23 '23 02:02 tysonmatanich