0
votes

I am trying to pass a props called user through stack navigation to my many page components and it isn't working for some reason. Yet the props could be passed from Tab Navigation to this Stack Navigation component (i am using nested navigation).

const StackNavigator = (props) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        options={{ headerShown: false }}
      >
          {props => <Home user={props.user} />}
      </Stack.Screen>
        <Stack.Screen
            name="Necessities"
            options={{ headerShown: false }}
        >
            {props => <Necessities user={props.user} />}
        </Stack.Screen>
        <Stack.Screen
            name="Entertainment"
            options={{ headerShown: false }}
        >
            {props => <Entertainment user={props.user} />}
        </Stack.Screen>
        <Stack.Screen
            name="Personal"
            options={{ headerShown: false }}
        >
            {props => <Personal user={props.user} />}
        </Stack.Screen>
      <Stack.Screen
        name="TransactionPage"
        options={{ headerShown: true }}
        component={TransactionPage}
      />
    </Stack.Navigator>
  );
};

I'm using the method from the documentation, https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props yet it doesn't work??? When I go to any of my components such as Personal , props is undefined.

2

2 Answers

0
votes

If you get an undefined props you should pass {...props} and debug whether user is inside props and what props your <Home /> is receiving

//To debug what props you is passing
<Stack.Screen
  name="Home"
  options={{ headerShown: false }}
>
    {props => <Home {...props} />}
</Stack.Screen>
0
votes

It doesn't work because you have 2 variables named props and you're referencing the wrong one

const StackNavigator = (props) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        options={{ headerShown: false }}
      >
          {props => <Home user={props.user} />} // this `props` is for the screen, not from the parent props

You need to do something like this:

const StackNavigator = (parentProps) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        options={{ headerShown: false }}
      >
          {props => <Home {...props} user={parentProps.user} />} // use `parentProps` instead of `props`

But it's not really an ideal way that you manually pass the prop to every screen. you should use React Context instead which is better and it'll simplify your code.