Jed
Jed

Reputation: 1074

React Navigation changing tab icons on tab navigator dynamically

So I am new to react native and redux. The app is already configured (by someone else) to have react-navigation and redux. Now we're using a TabNavigator (bottom) for our menu and this TabNavigator also contains the Login button. Now what I want to do is when the user logs in, the Login button (with text and icon) becomes Logout.

Is there a way to do that? Also my TabNavigator is in a separate file.

What I want is something like this:

TabNavigator(
  {
    ...other screens,
    //show this only if not logged in
    Login: {
      screen: LoginScreen
    },
    //show this only if logged in
    Logout: {
      screen: //There should be no screen here just the logout functionality
    }
  },
  {...options here}
)

Thanks in advance.

Upvotes: 0

Views: 2681

Answers (1)

Alexander Vitanov
Alexander Vitanov

Reputation: 4141

You can do it using Redux:

AuthIcon.js:

const LOGGED_IN_IMAGE = require(...)
const LOGGED_OUT_IMAGE = require(...)

class AuthIcon extends React.Component {
  render() {
    const { loggedIn, focused, tintColor } = this.props
     // loggedIn is what tells your app when the user is logged in, you can call it something else, it comes from redux
    return (
       <View>
         <Image source={loggedIn ? LOGGED_IN_IMAGE : LOGGED_OUT_IMAGE} resizeMode='stretch' style={{ tintColor: focused ? tintColor : null, width: 21, height: 21 }} />
      </View>
    )
  }
}

const ConnectedAuthIcon = connect(state => {
   const { loggedIn } = state.auth
   return { loggedIn }
})(AuthIcon)

export default ConnectedAuthIcon;

then inside your TabNavigator file:

import ConnectedAuthIcon from './AuthIcon.js'

export default TabNavigator({
  Auth: {
    screen: Auth,
    navigationOptions: ({ navigation }) => ({
      tabBarLabel: null,
      tabBarIcon: ({ tintColor, focused }) => <ConnectedAuthIcon tintColor={tintColor} focused={focused} />,
      title: "Auth"
    })
  }
})

Edit:

In your Auth.js:

class Auth extends React.Component {

  render() {
    const { loggedIn } = this.props
    if (loggedIn) {
      return <Profile />
    } else {
      return <Login />
    }
  }

}

export default connect(state => {
  const { loggedIn } = state.auth
  return { loggedIn }
})(Auth)

Upvotes: 1

Related Questions