mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
feat: add option to useTitle to restore title on un-mount
This commit is contained in:
commit
b8b3e479ce
@ -1,11 +1,22 @@
|
||||
import { useRef } from 'react';
|
||||
|
||||
function useTitle(title: string) {
|
||||
const t = useRef<string>();
|
||||
|
||||
if (t.current !== title) {
|
||||
document.title = t.current = title;
|
||||
}
|
||||
import { useRef, useEffect } from 'react';
|
||||
export interface UseTitleOptions {
|
||||
restoreOnUnmount?: boolean;
|
||||
}
|
||||
const DEFAULT_USE_TITLE_OPTIONS: UseTitleOptions = {
|
||||
restoreOnUnmount: false,
|
||||
};
|
||||
function useTitle(title: string, options: UseTitleOptions = DEFAULT_USE_TITLE_OPTIONS) {
|
||||
const prevTitleRef = useRef(document.title);
|
||||
document.title = title;
|
||||
useEffect(() => {
|
||||
if (options && options.restoreOnUnmount) {
|
||||
return () => {
|
||||
document.title = prevTitleRef.current;
|
||||
};
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}, []);
|
||||
}
|
||||
|
||||
export default typeof document !== 'undefined' ? useTitle : (_title: string) => {};
|
||||
|
||||
@ -13,4 +13,16 @@ describe('useTitle', () => {
|
||||
hook.rerender('My other page title');
|
||||
expect(document.title).toBe('My other page title');
|
||||
});
|
||||
|
||||
it('should restore document title on unmount', () => {
|
||||
renderHook(props => useTitle(props), { initialProps: 'Old Title' });
|
||||
expect(document.title).toBe('Old Title');
|
||||
|
||||
const hook = renderHook(props => useTitle(props.title, { restoreOnUnmount: props.restore }), {
|
||||
initialProps: { title: 'New Title', restore: true },
|
||||
});
|
||||
expect(document.title).toBe('New Title');
|
||||
hook.unmount();
|
||||
expect(document.title).toBe('Old Title');
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user