'How to set document title by React Native Web with react-navigation?
My web application is created by React Native Web with react-navigator.
react-navigator sets RouteName as document.title in default.
ex.
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="root" component={RootScreen} />
<Stack.Screen name="search" component={SearchScreen} />
</Stack.Navigator>
generates
...
<head>
<title>root</title>
...
What I want
Changing document.title on demand.
What I tried but not works
try to access document object directly, but below code does not works.
export default function RootScreen({ navigation }) {
useEffect(() => {
document.title = `My Web App | ${someMessage}`
})
Solution 1:[1]
I figured out that Expo for Web basically sets the screen title as the document title. So I did something like this:
import { Platform } from 'react-native';
const title = (text) => Platform.select({ web: `My Web App | ${text}`, default: text });
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="root" component={RootScreen} options={{ title: title('root') }} />
<Stack.Screen name="search" component={SearchScreen} options={{ title: title('search') }} />
</Stack.Navigator>
You can then amend the title
function to return the expected title for your various screens.
Solution 2:[2]
This has taken me the best part of my morning to figure out. There is a way to set the title in one place, rather than on each screen.
<NavigationContainer
documentTitle={{
formatter: (options, route) =>
`${options?.title ?? route?.name} - My Cool App`,
}}
>
https://reactnavigation.org/docs/navigation-container/#documenttitle
As you are making this change on the Navigation Container, this also works with nested navigations.
Solution 3:[3]
You can call navigation.setOptions({ title: 'some title' })
within your react components
https://reactnavigation.org/docs/headers/#updating-options-with-setoptions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ericluwj |
Solution 2 | Daniel P |
Solution 3 | Miro |