Pass Props StackNavigator

Ansyori picture Ansyori · Oct 31, 2017 · Viewed 32.7k times · Source

i try to pass props on stacknavigator, here my code

how to pass 'myprops' on StackNavigator area?

thanks

Answer

Ashwin Mothilal picture Ashwin Mothilal · Nov 3, 2017

React Navigation < 5

If you want to pass props in that place you have to use it like this.

const MainCart = StackNavigator({
 Cart: {
    screen: props=> <CartScreen {...props} screenProps={other required prop}>
 },
 Checkout: {
    screen: COScreen
 }

If you want to pass props when navigating the solution by Sagar Chavada is useful

React Navigation - 5

You have to either use React Context(recommended) or a render callback to solve this. Documentation link

Below example shows how to do with React Context

In your parent of the navigator file create a context

<AppContext.Provider value={other required prop}>
   <YourNavigator/>
</AppContext.Provider>

In your navigator file

const YourNavigator = () => (
  <AppStack.Navigator>
     <AppScreen.Screen name={"routeName"} component={AppContextWrapper}/>
  </AppStack.Navigator>

const AppContextWrapper = ({ navigation, route }) => (
  <AppContext.Consumer>
    {(other required prop) => (
       <YourScreenComponent {...other required prop}/>
    )}
  </AppContext.Consumer>
);

another easy (not recommended) - Callback method

<Stack.Screen name="Home">
  {props => <HomeScreen {...props} extraData={someData} />}
</Stack.Screen>

Note: By default, React Navigation applies optimizations to screen components to prevent unnecessary renders. Using a render callback removes those optimizations. So if you use a render callback, you'll need to ensure that you use React.memo or React.PureComponent for your screen components to avoid performance issues.