Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Props StackNavigator

Tags:

i try to pass props on stacknavigator, here my code

const MainCart = StackNavigator({    Cart: {      screen: CartScreen    },    Checkout: {      screen: COScreen    }      /* how to pass 'myprops' in this area? */    });      export default class ReactNative_RefreshControl extends Component {      constructor(props) {      super(props)    }      render() {      console.log('ReactNative_RefreshControl this.props.myparam : ' + this.props.myparam);      return <MainCart myprops = {        this.props.myparam      }      />;        //https://reactnavigation.org/docs/navigators/stack#Navigator-Props    }      }

how to pass 'myprops' on StackNavigator area?

thanks

like image 442
Ansyori Avatar asked Oct 31 '17 03:10

Ansyori


People also ask

What is Createstacknavigator?

Provides a way for your app to transition between screens where each new screen is placed on top of a stack. By default the stack navigator is configured to have the familiar iOS and Android look & feel: new screens slide in from the right on iOS, fade in from the bottom on Android.


1 Answers

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.

like image 149
Ashwin Mothilal Avatar answered Sep 17 '22 15:09

Ashwin Mothilal