React Navigation on tab change

Viewed 26396

Without using Redux, how do I detect a tab change with a react navigation tab navigator?

I know I need to somehow use onNavigationStateChange but I can't figure out how to update the current view.

export default () => <MyTabNav
    ref={(ref) => { this.nav = ref; }}
    onNavigationStateChange={(prevState, currentState) => {
        //call function on current view
    }}
/>;
5 Answers

Actually, you can add an special listener in your component

componentDidMount () {
    this.props.navigation.addListener('willFocus', (route) => { //tab changed });
} 

If you are using react-navigation version 5, then you can add tab-press listener right in your tab screen definition, to do some pre-processing, as mentioned in docs

<Tab.Navigator>
    <Tab.Screen
        component={HomeScreen}
        name="HomeScreen"
        listeners={{
          tabPress: e => {
            if (userIsNotLoggedIn) {
              // Prevent default action
              e.preventDefault();
              navigation.navigate("LoginScreen");
            }
          },
        }}
      />
      <Tab.Screen
        ../>
</Tab.Navigator>

Explanation: When Home tab will be clicked in BottomBar, and if user is not logged in, the HomeScreen won't open and instead LoginScreen will open(Note: LoginScreen is navigation name which will be registered some where with a screen). But if user is logged in, then it will behave normally.

And if you intend to use the Window properties, you can easily do this in react.

Keep a check whether window is present before return inside of render.

if (typeof window !== "undefined") {
window.addEventListener('visibilitychange, () => {
window.document.title = window.document.hidden;
console.log(document.hidden ? "Out" : "In");
this.props.doFunction();

}

Related