javascriptreact-nativereact-routerreact-native-navigationwix-react-native-navigation

How to access a variable in header tab navigation in react native


I have a switch in my tab header and I want to get the value of switch value in my header every time when I toggle the switch. how can I get that value?

const navigationOptions = ({ navigation }) => {
  const { params = {} } = navigation.state;

  return {
    title: "Home",
    headerTitleStyle: {
      flex: 1,
      textAlign: "center",
      color: "white",
      fontSize: 20,
    },
    headerTintColor: "white",
    headerStyle: {
      backgroundColor: "#4169E1",
    },
    headerRight: (
      <Switch
        onValueChange={() => params.handleSave()}
        value={this.navigation.state.switchValue}
      />
    ),
  };
};

class HomeScreen extends React.Component {
  state = { switchValue: false };
  componentDidMount() {
    this.props.navigation.setParams({ handleSave: this.toggleSwitch });
  }
  toggleSwitch = (value) => {
    //onValueChange of the switch this function will be called
    this.setState({ switchValue: value });
    //state changes according to switch
    //which will result in re-render the text
  };
}


Solution

  • I just called this.props.navigation.setParams every time I update the params value in navigation options

    toggleSwitch = (value) => {
      this.setState({ switchValue: value });
      this.props.navigation.setParams({
        switchValue: holder,
      });
    };