Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation on tab change

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
    }}
/>;
like image 472
TJ Gillis Avatar asked May 16 '17 11:05

TJ Gillis


People also ask

How do you navigate between tabs in react?

To open a link in a new tab in React, use the <a> element and set its target prop to _blank , e.g. <a href="https://google.com" target="_blank" rel="noopener noreferrer"></a> . The _blank value means that the resource is loaded into a new tab. Copied!

How do I use tab Navigation with stack Navigation?

Tab navigator nested inside the initial screen of stack navigator - New screens cover the tab bar when you push them. Drawer navigator nested inside the initial screen of stack navigator with the initial screen's stack header hidden - The drawer can only be opened from the first screen of the stack.

What is tab Navigation?

In computing, tabbing navigation is the ability to navigate between focusable elements (such as hyperlinks and form controls) within a structured document or user interface (such as HTML) with the tab key of a computer keyboard.


2 Answers

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.

like image 150
Sanjeev Avatar answered Oct 24 '22 12:10

Sanjeev


Actually, you can add an special listener in your component

componentDidMount () {
    this.props.navigation.addListener('willFocus', (route) => { //tab changed });
} 
like image 44
OsDev Avatar answered Oct 24 '22 12:10

OsDev