-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathuseIsHighlighted.ts
More file actions
35 lines (28 loc) · 917 Bytes
/
useIsHighlighted.ts
File metadata and controls
35 lines (28 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useCallback, useEffect, useState } from "preact/hooks";
// Check if window is defined (so if in the browser or in node.js).
const isBrowser = typeof window !== "undefined";
/**
* Returns `true` if the URL hash is equal to the given `id`
* @param id The id to match the hash against
* @returns Boolean indicating whether the hash matches the given id
*/
export default function useIsHighlighted(id: string): boolean {
if (isBrowser) {
const hash = useHash();
return hash === `#${id}`;
}
return false;
}
const useHash = () => {
const [hash, setHash] = useState(() => window.location.hash);
const onHashChange = useCallback(() => {
setHash(window.location.hash);
}, []);
useEffect(() => {
window.addEventListener("hashchange", onHashChange);
return () => {
window.removeEventListener("hashchange", onHashChange);
};
}, [onHashChange]);
return hash;
};