File tree 2 files changed +31
-8
lines changed
2 files changed +31
-8
lines changed Original file line number Diff line number Diff line change 1
- import { useRef } from 'react' ;
2
-
3
- function useTitle ( title : string ) {
4
- const t = useRef < string > ( ) ;
5
-
6
- if ( t . current !== title ) {
7
- document . title = t . current = title ;
8
- }
1
+ import { useRef , useEffect } from 'react' ;
2
+ export interface UseTitleOptions {
3
+ restoreOnUnmount ?: boolean ;
4
+ }
5
+ const DEFAULT_USE_TITLE_OPTIONS : UseTitleOptions = {
6
+ restoreOnUnmount : false ,
7
+ } ;
8
+ function useTitle ( title : string , options : UseTitleOptions = DEFAULT_USE_TITLE_OPTIONS ) {
9
+ const prevTitleRef = useRef ( document . title ) ;
10
+ document . title = title ;
11
+ useEffect ( ( ) => {
12
+ if ( options && options . restoreOnUnmount ) {
13
+ return ( ) => {
14
+ document . title = prevTitleRef . current ;
15
+ } ;
16
+ } else {
17
+ return ;
18
+ }
19
+ } , [ ] ) ;
9
20
}
10
21
11
22
export default typeof document !== 'undefined' ? useTitle : ( _title : string ) => { } ;
Original file line number Diff line number Diff line change @@ -13,4 +13,16 @@ describe('useTitle', () => {
13
13
hook . rerender ( 'My other page title' ) ;
14
14
expect ( document . title ) . toBe ( 'My other page title' ) ;
15
15
} ) ;
16
+
17
+ it ( 'should restore document title on unmount' , ( ) => {
18
+ renderHook ( props => useTitle ( props ) , { initialProps : 'Old Title' } ) ;
19
+ expect ( document . title ) . toBe ( 'Old Title' ) ;
20
+
21
+ const hook = renderHook ( props => useTitle ( props . title , { restoreOnUnmount : props . restore } ) , {
22
+ initialProps : { title : 'New Title' , restore : true } ,
23
+ } ) ;
24
+ expect ( document . title ) . toBe ( 'New Title' ) ;
25
+ hook . unmount ( ) ;
26
+ expect ( document . title ) . toBe ( 'Old Title' ) ;
27
+ } ) ;
16
28
} ) ;
You can’t perform that action at this time.
0 commit comments