Configuring the header bar
We've seen how to configure the header title already, but let's go over that again before moving on to some other options — repetition is key to learning!
Setting the header title
A Screen component accepts options
prop which is either an object or a function that returns an object, that contains various configuration options. The one we use for the header title is title
, as shown in the following example.
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My home' }}
/>
</Stack.Navigator>
);
}
Using params in the title
In order to use params in the title, we need to make options
prop for the screen a function that returns a configuration object. It might be tempting to try to use this.props
inside of options
, but because it is defined before the component is rendered, this
does not refer to an instance of the component and therefore no props are available. Instead, if we make options
a function then React Navigation will call it with an object containing { navigation, route }
- in this case, all we care about is route
, which is the same object that is passed to your screen props as route
prop. You may recall that we can get the params through route.params
, and so we do this below to extract a param and use it as a title.
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My home' }}
/>
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={({ route }) => ({ title: route.params.name })}
/>
</Stack.Navigator>
);
}
The argument that is passed in to the options
function is an object with the following properties:
navigation
- The navigation prop for the screen.route
- The route prop for the screen
We only needed the route
prop in the above example but you may in some cases want to use navigation
as well.
Updating options
with setOptions
It's often necessary to update the options
configuration for the active screen from the mounted screen component itself. We can do this using navigation.setOptions
/* Inside of render() of React class */
<Button
title="Update the title"
onPress={() => navigation.setOptions({ title: 'Updated!' })}
/>