Search code examples
reactjsreact-nativereduxreact-navigation

react navigation v3 set screenProps through AppContainer


I need to pass theme settings to navigation options of each screen. Settings are stored in redux. In old version I would write something like that:

const AppNavigator = StackNavigator({
  Home: { screen: MainList },
  Settings: { screen: Settings },
  NewEvent: { screen: NewEvent },
  Contacts: { screen: Contacts },
  Map: { screen: Map},
})

And in render function...

<AppNavigator 
   screenProps={{
     settings: this.props.settings,
     headerTintColor: '#ffffff'
   }}
/>

...where props.settings is a part of redux state. Which is used inside navigationOptions

static navigationOptions = ({ navigation, screenProps }) => {
  let settings = screenProps.settings;
  let theme = settings? settings.theme: null;

  return {
    title: strings.account,
    headerTintColor: screenProps.headerTintColor,
    headerStyle: {backgroundColor: theme? theme.def.primaryColor: null}
  };
};

But how should I do this now when I must wrap my Navigators with createAppContainer? Using navigation.setParams makes a visible delay in emulator so its not a proper solution for me... Keep in mind theme can be changed at any time!


Solution

  • Well) Turnsout you can achive that by creating a custom navigator like this:

    class NavWrapper extends Component {
      static router = AppNavigator.router;
      render() {
        const { navigation } = this.props;
    
        return <AppNavigator
          navigation={navigation}
          screenProps={{
            settings: this.props.settings,
            headerTintColor: '#ffffff'
          }}
        />;
      }
    }
    
    const AppNavWrapper = connect(state => ({settings: state.settings}))(NavWrapper);
    const AppContainer = createAppContainer(AppNavWrapper);
    

    And then in your root component

    render() {
      return (
        <AppContainer/>
      );
    }
    

    Hope that helps :)