bryan
bryan

Reputation: 9399

Custom function in headerRight of StackNavigator in react native

I have the following component that I'm trying to have some left and right header buttons in the header area. However, I am having trouble getting my function logout to call. Does anyone know what I might be doing wrong and how to fix it?

I'm using react-navigation

export default class HomeScreen extends Component<Props> {

  constructor(props) {
    super(props);
    this.state = { refreshing: false }
  }

  logout = async () => {
    alert("HI");
    AsyncStorage.setItem('current_appid', '');
    this.props.navigation.navigate('Identification');
  }

  static navigationOptions = {
    headerStyle: { backgroundColor:"#fff", height:60},
    headerTitleStyle: { color:"#3F61E7", fontSize: 24},
    headerBackground: "#fff",
    title: 'My Title',
    headerRight: <Text style={{marginRight:15, color:"#3F61E7", fontWeight:"400", fontSize:16}}>Settings</Text>,
    headerLeft: <Text onPress={async () => this.logout} style={{marginLeft:15, color:"#3F61E7", fontWeight:"400", fontSize:16}}>Log Out</Text>
  };

}

Upvotes: 1

Views: 2927

Answers (1)

MaieonBrix
MaieonBrix

Reputation: 1624

UPDATE :

In navigationOptions, you, and I quote grabbou on this issue :

You can't access state. What you can do is either use this.context, externalise props (parent component / redux) or see this thread #145

And dmhood :

you can't call this.saveDetails() from a static context since the actual saveDetails method is a class method. You would need to make saveDetails static or just some helper function outside of the class.

One of the solution exposed in the #145 issue, and one that I used for an app that I am currently working on, is to use setParams on your componentDidMount lifecycle hook like so :

componentDidMount() {
   this.props.navigation.setParams({ yourfunction: this.yourfunction });
}

Then you can use the other way to declare your navigationOptions and this by declaring a function that takes in parameters the navigation object (with the navigation state (that contains the params !!))

( see an example on the main repo here)

  YourComponent.navigationOptions = props => {
      const { navigation } = props;
      const { state } = navigation;
      const { params } = state;
      return {
         /* your navigationOptions props */,
         headerRight: <Button onPress={() => params.yourfunction()} />
      }
  }

UPDATE 2 :

If you want to stick with the other syntax, just remember that your headerRight component receives the navigation object as a props containing your navigation state and its params !

UPDATE 3 :

A good discussion about how to solve this particular problem can be found on the official repo here

Upvotes: 1

Related Questions