Skip to content

Commit

Permalink
feat: add option to useTitle to restore title on un-mount
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jan 14, 2020
2 parents 75835cb + 8faa71f commit b8b3e47
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/useTitle.ts
Original file line number Diff line number Diff line change
@@ -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) => {};
12 changes: 12 additions & 0 deletions tests/useTitle.test.tsx → tests/useTitle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});

0 comments on commit b8b3e47

Please sign in to comment.