Dynamically change header title on react navigation 5.x
Asked Answered
C

3

6

I have recently updated my project to react navigation 5.x. In earlier version we used to set header title as follows :

static navigationOptions = ({ navigation }) => ({
        title: 'find',
});

This is not working on React Navigation 5.x. Please Suggest.

Cirrocumulus answered 29/5, 2020 at 7:28 Comment(0)
P
15

You can do it via 2 methods;

1: Set options to be a variable from your screen and keep your current code:

<Stack.Screen
  name="Label"
  component={Component}
  options={Component.navigationOptions}
/>

// component
static navigationOptions = {
  title: 'find',
};

2: By using setOptions in your component:

<Stack.Screen
  name="News"
  component={News}
  options={{
    title: 'Default',
  }}
/>

// component
this.props.navigation.setOptions({title: 'find'});
Polack answered 7/9, 2020 at 22:3 Comment(0)
C
1

After going through various SO posts and documents I found the following ways to do this -

In the Component using setOptions

this.props.navigation.setOptions({title: 'TitleSetInComponent'});

Can also give a default title in createStackNavigator();

<Stack.Screen
  name="myComponent"
  component={MyComponent}
  options={{
    title: 'TitleSetInStackNavigator',
  }}
/>

In createStackNavigator(); using navigationOptions as options

<Stack.Screen
name="myComponent"
component={MyComponent}
options={MyComponent.navigationOptions}
/>

// MyComponent
static navigationOptions = {
title: 'TitleSetInComponent',
};
Cirrocumulus answered 26/8, 2022 at 14:35 Comment(2)
How is this different from my answer?Polack
@AbdulSadikYalcin - Yes you are right, both are similar since yours was an earlier reply. I am marking yours as correct.Cirrocumulus
Q
0

Hey you should definitly check out this: https://reactnavigation.org/docs/screen-options-resolution/

Here you can see how to set the title for each tab and each stack. Read threw the page and look at this func:

function getHeaderTitle(route) {
  // Access the tab navigator's state using `route.state`
  const routeName = route.state
    ? // Get the currently active route name in the tab navigator
      route.state.routes[route.state.index].name
    : // If state doesn't exist, we need to default to `screen` param if available, or the initial screen
      // In our case, it's "Feed" as that's the first screen inside the navigator
      route.params?.screen || 'Feed';

  switch (routeName) {
    case 'Feed':
      return 'News feed';
    case 'Profile':
      return 'My profile';
    case 'Account':
      return 'My account';
  }
}
Quag answered 29/5, 2020 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.