26 lines
755 B
TypeScript
26 lines
755 B
TypeScript
|
|
import { useCallback, useEffect, useState } from 'react';
|
||
|
|
|
||
|
|
function readHash(defaultId: string): string {
|
||
|
|
const hash = window.location.hash.slice(1); // strip leading '#'
|
||
|
|
return hash || defaultId;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useHashTab(defaultId: string): [string, (id: string) => void] {
|
||
|
|
const [activeId, setActiveId] = useState<string>(() => readHash(defaultId));
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
function onHashChange() {
|
||
|
|
setActiveId(readHash(defaultId));
|
||
|
|
}
|
||
|
|
window.addEventListener('hashchange', onHashChange);
|
||
|
|
return () => window.removeEventListener('hashchange', onHashChange);
|
||
|
|
}, [defaultId]);
|
||
|
|
|
||
|
|
const navigate = useCallback((id: string) => {
|
||
|
|
window.location.hash = id;
|
||
|
|
setActiveId(id);
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
return [activeId, navigate];
|
||
|
|
}
|