How to pass props to 'screens'/components in react-navigation
for those who are looking for a React Navigation 5 solution, you can use initialParams
like this:
<Stack.Navigator> <Stack.Screen name="screenName" component={screenComponent} initialParams={{key: value}} /></Stack.Navigator>
You could pass a props using function. Try this
import React from 'react';import ExplorePage from './app/tabs/ExplorePage';import {createBottomTabNavigator} from 'react-navigation';...other importsclass App extends React.Component { state = { parentState: 'testing testing', } render() { // old // const MainScreenNavigator = mainScreenNavigator(this.state.parentState); const MainScreenNavigator = mainScreenNavigator(this.state); return ( <MainScreenNavigator /> ) }}const mainScreenNavigator = value => createBottomTabNavigator( { // Home: { screen : props => <ExplorePage {...props} parentState={value} /> }, Home: { screen : props => <ExplorePage {...props} {...value} /> }, Search: {screen: SearchPage}, Favorites: {screen: FavoritesPage}, });export default App;
Edit
First thing, I changed your MainScreenNavigator
to be a function, as it is accepting state values dynamically.
Second thing, Instead of directly assigning { screen : Component }
, I used function. This is the feature provided by reactnavigation. You can find about this in the documentation. ReactNavigation
If you want to pass multiple attributes then you can use es6 spread operator, as shown in the edit. {...value}
, this will pass all the property of value to that component.
You should use Navigator Props "screenProps" as mentionned in API:
screenProps - Pass down extra options to child screens
On child screen, just take props via this.props.screenProps