Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Header title in navigationOptions from constructor in react-native app?

In my react-native project I have use DrawerNavigator from which I navigate to SwitchAccount page. In SwitchAccount page I have use Tabs from react-native-tabs. Below is code where I use

    render() {
      return (
     <View style={[styles.container]}>
      // Here _renderTab function return component based on selectedService
      {this._renderTab(this.state.selectedService)} 
      <TabBarContainer
          selectedService={this.state.selectedService}
          onTabChange={this._switchService}
        />
     </View>
    ); 
  }

When I click on tab then it change the state and then I get new component returned by _renderTab function. All works properly, but I want to change Header title based on the component returned by the _renderTab function. What should I do? Is there any way to change Header title from constructor? Below is my code for navigationOptions in SwitchAccount page. There I want to change title from constructor.

    static navigationOptions = {
    title:'Filter',
    drawerLabel: 'Switch Account',
    drawerIcon: ({ tintColor }) => (
      <Icon
        name='md-switch'
        size={40}
        color='black'
      />
    ),
  };
like image 995
GAURAV Avatar asked Jun 19 '18 06:06

GAURAV


People also ask

How do you align a title Center in react native?

headerTitleStyle: { alignSelf: 'center' , textAlign:"center",flex:1 }, Worked for me!


1 Answers

One way would be to to use the navigation params. navigationOptions can be defined as a function (instead of an object), which receives an object containing the navigation object itself as one of its keys:

static navigationOptions = ({navigation}) => ({ /* ... */ })

This allows you to set the title dynamically by reading a param from the navigation object:

static navigationOptions = ({navigation}) => ({
    title: navigation.getParam('title', 'DefaultTitle'),
    /* ... */
})

Within one of you components you could then call the setParams function on the navigation object to set the title:

handleChangeTab = (tab) => {
    /* Your tab switching logic goes here */

    this.props.navigation.setParams({
        title: getTitleForTab(tab)
    })
} 

Note that the component must have been mounted by react-navigation in order to have access to the navigation prop, otherwise you'll either have to pass it from its parent or use the withNavigation HoC to wrap the component and have it receive the prop from there.

That said, have you considered using Tab navigation?

like image 182
Gian Marco Toso Avatar answered Nov 15 '22 05:11

Gian Marco Toso