Home > front end >  React Navigation: How to pass a prop to a screen in a nested navigator?
React Navigation: How to pass a prop to a screen in a nested navigator?

Time:02-17

In my React Native app I have the following TabNavigator nested inside an AppNavigator:

const TabNavigator = () => (
    <Tab.Navigator>
      <Tab.Screen component={Screen1} />
    </Tab.Navigator>
);

export const AppNavigator = () => {

  const [loading, setLoading] = useState(false);

  <Stack.Navigator>
    <Stack.Screen component={TabNavigator}/>
    <Stack.Screen component={OtherComponent1}/>
    <Stack.Screen component={OtherComponent2}/>
  </Stack.Navigator>
}

I want to pass the loading hook to Screen1.

What I've tried:

  1. Putting const TabNavigator etc inside AppNavigator. The problem with this is, AppNavigator re-renders a lot, and therefore Screen1 re-renders and flickers a lot.
  2. Passing loading as a prop to TabNavigator and Screen1, like <Stack.Screen component={() => <TabNavigator loading={loading}/>}/> and <Tab.Screen component={() => <Screen1 loading={props.loading}/>} />. The problem with this is is that it gives me this warning about passing an inline function.

What's the best way to approach this?

CodePudding user response:

You can use the Context API to pass the value. https://reactjs.org/docs/context.html

CodePudding user response:

you could pass it using options prop -

<Stack.Screen
    name="Home"
    component={HomeScreen}
    options={{ loading: loading }}
  />

as you can see here - react navigation docs

CodePudding user response:

<Stack.Screen
   name={name} 
   component={() => <TabNavigator loading={loading} {...props} />} 
/>
  • Related