React Navigation part 6: How to set and change the header title

Introduction :

By default, the name of a Stack screen is shown as the header title. For example, if we have one screen as below in the navigation container :

<Stack.Screen name="Home-Screen" component={HomeScreen} />

It will show Home-Screen as the header title.

React navigation provides a couple of different ways to change the header title. In this post, we will learn how to do that.

Using options prop :

Stack.Screen accepts one options prop. This prop can be one object or one function that returns one object. We can pass the title in this prop :

<NavigationContainer>
    <Stack.Navigator initialRouteName="HomeScreen">
    <Stack.Screen
        name="HomeScreen"
        component={HomeScreen}
        options={{title: 'Home Page'}}
    />
    <Stack.Screen
        name="DetailScreen"
        component={DetailScreen}
        options={{title: 'Detail Page'}}
    />
    </Stack.Navigator>
</NavigationContainer>

It will set the title of both screens as defined in options.

Dynamically set the title :

We may need to set the title dynamically. For example, we can start one screen from different parts of an App, and based on the provided props, we can show different layouts including different titles.

We can pass one function to options to do that. We will use the route props to access the title value.

For example, if we open the DetailScreen from HomeScreen like below :

<Button
    title="Click me"
    onPress={() =>
    navigation.navigate('DetailScreen', {title: 'Detail Page'})
    }
/>

We can set the title dynamically :

<Stack.Screen
    name="DetailScreen"
    component={DetailScreen}
    options={({route}) => ({title: route.params.title})}
/>