feat: add option to useTitle to restore title on un-mount

This commit is contained in:
Vadim Dalecky 2020-01-14 07:28:45 -08:00 committed by GitHub
commit b8b3e479ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 8 deletions

View File

@ -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) => {};

View File

@ -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');
});
});