1

I'm writing a React Native app and I'm using React Navigation (V2) with it. I want to update the navigationOptions and add a new button, after my component has updated. Here is the code with which I tried it:

  static navigationOptions = ({ navigation }) => {
    const options = {
      headerTitle: SCREEN_TEXT_MENU_HEADER,
      headerStyle: {
        borderBottomWidth: 0,
        marginBottom: -5
      }
    };
    if (navigation.getParam("drawer", true)) {
      options["headerLeft"] = (
        <HeaderIconButton
          onClick={() => {
            navigation.openDrawer();
          }}
          icon={require("../../assets/icons/burgerMenu.png")}
        />
      );
    }
    if (navigation.getParam("renderBillButton", false)) {
      options["headerRight"] = (
        <HeaderIconButton
          onClick={() => {
            navigation.navigate("BillScreen");
          }}
          type="primary"
          icon={require("../../assets/icons/euro.png")}
        />
      );
    }
    return options;
  };

  componentDidUpdate = prevProps => {
    const { navigation, orders } = this.props;
    if (prevProps.orders.length !== orders.length) {
      navigation.setParams({
        renderBillButton: orders.length > 0
      });
    }
  };

The problem with this approach is, that the navigationOptions do not get reset after componentDidUpdate(). How can I dynamically adjust the header with React Navigation?

halfer
  • 19,824
  • 17
  • 99
  • 186
J. Hesters
  • 13,117
  • 31
  • 133
  • 249

2 Answers2

0

You can use this.props.navigation.setParams() function to update the navigation state params.

Reference: https://reactnavigation.org/docs/en/headers.html#updating-navigationoptions-with-setparams

vahissan
  • 2,322
  • 16
  • 26
0

Okay here is what went wrong: I also had to call the same code within componentDidMount(), otherwise it would not affect the page upon loading. So in addition to the code of my question I added:

componentDidMount = () => {
  const { navigation, order } = this.props;
  navigation.setParams({
    renderBillButton: orders.length > 0
  });
}
J. Hesters
  • 13,117
  • 31
  • 133
  • 249
  • Could you help me with this please ? https://stackoverflow.com/questions/62034177/react-navigation-5-navigation-setparam-not-setting-parameter – newdeveloper May 27 '20 at 03:32