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

hashchange doesn't fire for relative links

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

Linking with just a fragment will trigger a hashchange event, but it doesn't appear to work if the href also includes the path.

Sample code showing the problem:

import { h, Component } from "preact";

export default class HashTest extends Component {
	updateHash = () => {
		this.setState({hash: location.hash});
	};

	componentDidMount() {
		window.addEventListener("hashchange", this.updateHash);
		this.updateHash();
	}

	componentWillUnmount() {
		window.removeEventListener("hashchange", this.updateHash);
	}

	render({}, {hash}) {
		return <div>
			<h1>Hash Link Test</h1>
			<p><a href="#bare">Fragment link</a></p>
			<p><a href="/hashtest#relative">Relative link</a></p>
			<p>The hash is: {hash}</p>
		</div>;
	}
}

vpzomtrrfrt avatar Aug 02 '19 16:08 vpzomtrrfrt

@vpzomtrrfrt is this mounted within a <Router>? If so <a href="/hashtest#relative"> will perform a Router update in addition to the hashchange. If not, it will perform a full page load. I'm not sure which is being used here.

developit avatar Oct 18 '19 17:10 developit

Here's the full test project: https://github.com/vpzomtrrfrt/hashchangetest

On the /hashtest page, the "Relative link" link doesn't trigger the hashchange event

vpzomtrrfrt avatar Oct 23 '19 20:10 vpzomtrrfrt

Rewrote test case for current version, issue is still present.

Looks like the working links aren't even being intercepted by preact-router, as it doesn't seem to support links other than root-relative.

vpzomtrrfrt avatar Jun 08 '20 22:06 vpzomtrrfrt

yup, that's correct. preact-router only supports root-relative urls.

marvinhagemeister avatar Jun 08 '20 22:06 marvinhagemeister