UNPKG

925 BTypeScriptView Raw
1import type {
2 NavigationContainerRef,
3 ParamListBase,
4} from '@react-navigation/core';
5import * as React from 'react';
6
7import type { DocumentTitleOptions } from './types';
8
9/**
10 * Set the document title for the active screen
11 */
12export default function useDocumentTitle(
13 ref: React.RefObject<NavigationContainerRef<ParamListBase>>,
14 {
15 enabled = true,
16 formatter = (options, route) => options?.title ?? route?.name,
17 }: DocumentTitleOptions = {}
18) {
19 React.useEffect(() => {
20 if (!enabled) {
21 return;
22 }
23
24 const navigation = ref.current;
25
26 if (navigation) {
27 const title = formatter(
28 navigation.getCurrentOptions(),
29 navigation.getCurrentRoute()
30 );
31
32 document.title = title;
33 }
34
35 return navigation?.addListener('options', (e) => {
36 const title = formatter(e.data.options, navigation?.getCurrentRoute());
37
38 document.title = title;
39 });
40 });
41}