Skip to content

Instantly share code, notes, and snippets.

@Tam
Last active December 10, 2020 15:47
Show Gist options
  • Save Tam/1390904802192f16d3d2c0409359617b to your computer and use it in GitHub Desktop.
Save Tam/1390904802192f16d3d2c0409359617b to your computer and use it in GitHub Desktop.
Preact Router match hook (useMatch)
import { getCurrentUrl, exec, subscribers } from 'preact-router';
import { useEffect, useState } from 'preact/hooks';
/**
* Hook to check if the given path matches the current URL
*
* const [matches, { path }] = useMatch('/my/:path?');
*
* @param {string} path - The path to check against
* @return {[boolean, Object]}
*/
export default function useMatch (path) {
const [nextUrl, setNextUrl] = useState(getCurrentUrl());
useEffect(() => {
const update = url => setNextUrl(url);
subscribers.push(update);
return () => subscribers.splice(subscribers.indexOf(update) >>> 0, 1);
}, [setNextUrl]);
const matches = exec(nextUrl.replace(/\?.+$/,''), path, {});
return [matches !== false, matches || {}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment