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 :

    <Stack.Navigator initialRouteName="HomeScreen">
        options={{title: 'Home Page'}}
        options={{title: 'Detail Page'}}

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 :

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

We can set the title dynamically :

    options={({route}) => ({title: route.params.title})}