Gary Lim
Gary Lim

Reputation: 11

How to Access the navigation prop from any component?

I have tried multiple ways in different stackoverflow post and also the original documentation from https://reactnavigation.org/docs/connecting-navigation-prop/ but still failed to solve my issue.

I have a Login Screen, after i navigate to a Home Screen, From Home screen i wanted to navigate to another screen but the navigation props is undefined.

Tried following the documentation but still failed to do so.

Please help thank you so much.

I have imported my App.js, HomePage.js (The one i wanted to navigate to another Screen but failed to)

Currently the code i have is based on the documentation but is having no effect when button is clicked.

import * as RootNavigation from '../config/RootNavigation';
const HomePage = () => {

    const onLogOut = () => {
        alert("Logged out")
        firebase.auth().signOut();
    }

    const inventoryOnPress = () => {
        RootNavigation.navigate('InventoryScreen')
    }


    return(
        <View>
                <CardComponent 
                style={styles.cardBackground} 
                title="Inventory"
                onPress={inventoryOnPress}/>
        </View>
    );
}

export default HomePage;

   
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { navigationRef } from './src/config/RootNavigation';

const Stack = createStackNavigator();
function NavStack() {

  const [initialPage,setInitialPage] = useState('LoginScreen');
  return(
    <Stack.Navigator
    initialRouteName={initialPage}
    screenOptions={{
      headerTitleAlign:'center',
      headerStyle: {
        backgroundColor: '#621FF7'
      }
    }}
    >
      <Stack.Screen 
              name="LoginScreen"
              component={LoginPage}
            />
            <Stack.Screen 
              name="HomeScreen"
              component={HomePage} 
              headerLeft={null}
            />
            <Stack.Screen 
              name="SignUpScreen"
              component={SignUpPage}
            />
            <Stack.Screen 
              name="InventoryScreen"
              component={InventoryPage}
            />

    </Stack.Navigator>
  )
}


function App() {
      return (
        <NavigationContainer ref={navigationRef}>
           <NavStack />
        </NavigationContainer>
      );
    }
}

// RootNavigation.js

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}

// add other navigation functions that you need and export them

Upvotes: 0

Views: 3188

Answers (2)

Rohit Aggarwal
Rohit Aggarwal

Reputation: 1190

navigation prop is available to every individual screen enclosed in NavigationContainer.
You can access it as follows

const inventoryOnPress = () => {
       props.navigation.navigate('InventoryScreen')
    }

Refer this article for more detailed information for same.

Update

If you are not able to get navigation prop using ref to NavigationContainer then it implies your component is not rendered yet and has applied some actions on it.
So to avoid this use navigationRef.current.getRootState() to see if this returns an valid object and navigate consequently.

Upvotes: 1

sudoDeznit
sudoDeznit

Reputation: 108

Please don't post firebase or any other API key on SO.

There are a few issues how you are handling navigation (authentication) here. Please read the docs Auth Flow for detailed answer. One issue is when user is logged in you are returning just the HomeScreen and there is no NavigationContainer returned, this is one of the reason you don't have access to navigation prop in HomePage.

So basically in your App() fn you can return something like this

<NavigationContainer>
<Stack.Navigator>
isSignedIn ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Profile" component={ProfileScreen} />
    <Stack.Screen name="Settings" component={SettingsScreen} />
  </>
) : (
  <>
    <Stack.Screen name="SignIn" component={SignInScreen} />
    <Stack.Screen name="SignUpScreen" component={SignUpPage} />
  </>
)
</Stack.Navigator>
</NavigationContainer>

Now to get navigation prop in your HomeScreen you can use useNavigation Hook if you prefer hooks.

import { useNavigation } from '@react-navigation/native';

const HomePage = () => {
const navigation = useNavigation();

  return (
    <Button
      title="Navigate To Profile"
      onPress={() => navigation.navigate("Profile")}
    />
  );
}

Upvotes: 1

Related Questions