Abhishek Singh
Abhishek Singh

Reputation: 9178

Using Redux state in defaultNavigationOptions

I am using React-navigation and redux in my app.

I have to change header color according to state. I have saved color inside state and my colors came from Api call.

I have used navigationOptions with redux according to docs.

static navigationOptions = ({ navigation }) => ({
    title: "MyApp",
    headerStyle: {
        backgroundColor: navigation.getParam('primary_color'),
    },
    headerTintColor: navigation.getParam('primary_color_text')
})

componentWillMount() {
    this.props.navigation.setParams({
        ...this.props.appSettings
    });
}

But I'm getting white header for 1 sec then my color one, due to props setting by params. So is there any way I can connect defaultNavigationOptions?

Upvotes: 3

Views: 412

Answers (1)

Amsvartner
Amsvartner

Reputation: 793

You can change defaultNavigationOptions in the same way you do navigationOptions, any parameters you set can be accessed there as well.


defaultNavigationOptions = ({ navigationData }) => {
    let params = navigationData.navigation.state.params || {...yourDefaultParams};

    return {
        title: "MyApp",
        headerStyle: {
            backgroundColor: params["primary_color"],
        },
        headerTintColor: params["primary_color_text"],
    };
});

It will, however give the same delay on changing the colors. You will have to attack the problem from a different angle. Have a look a Edward Starlight's suggested solution:

react navigation v3 set screenProps through AppContainer

You can achieve 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/>
  );
}

Upvotes: 2

Related Questions