Last active
December 10, 2020 15:47
-
-
Save Tam/1390904802192f16d3d2c0409359617b to your computer and use it in GitHub Desktop.
Preact Router match hook (useMatch)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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