beddow
beddow

Reputation: 53

how to render conditionally within the react native stack navigator header?

I'm trying to render the headerRight conditionally based on a navigation param. I am currently trying this in the static navigationOptions. Here is my code but nothing is rendering to the screen

static navigationOptions = ({navigation}) => ({
headerRight : () => {
  if (navigation.state.params.user.following) {
    return (
        <TouchableOpacity
          onPress={() => this.followUser()}>
          <Icon2 name="ios-person-add-outline" size={35} />
        </TouchableOpacity>
    )}  else {
    return (
          <TouchableOpacity
            onPress={() => this.unfollowUser()}>
            <Icon name="user-times" size={20} />
          </TouchableOpacity>
        )}
    },
})

Can this be done or will I need to use a custom header here?

Any help would be hugely appreciated! Thanks!

Solution:

remove the anonymous function and implement the conditional syntax recommended by soutot

static navigationOptions = ({navigation}) => ({
  headerRight :  navigation.state.params.otherUser.following ?
    ( <TouchableOpacity
         onPress={() => this.followUser()}>
         <Icon2 name="ios-person-add-outline" size={35} />
      </TouchableOpacity> )
    :
    ( <TouchableOpacity
         onPress={() => this.unfollowUser()}>
         <Icon name="user-times" size={20} />
      </TouchableOpacity> )
    })

Upvotes: 0

Views: 2490

Answers (1)

soutot
soutot

Reputation: 3671

You are using a comma (,) after your 'else' statement. Also you can try something like this

return(
navigation.state.params.user.following ?
<TouchableOpacity
  onPress={() => this.followUser()}>
  <Icon2 name="ios-person-add-outline" size={35} />
</TouchableOpacity>
:
<TouchableOpacity
  onPress={() => this.unfollowUser()}>
  <Icon name="user-times" size={20} />
</TouchableOpacity>
);

For more info about conditional rendering, check the following docs: https://facebook.github.io/react/docs/conditional-rendering.html

https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

Hope it helps

Upvotes: 1

Related Questions