I am trying to pass data (object) inside Navigator Stack to root Screen, but in js component its become undefined. Please need your help, what I am dooing wrong?
So, in my App.js I have a state:
const [isSignedIn, setIsSignedIn] = useState(false); /// in code deeper it transformed to 'true'
this state I pass like object from App.js to a navigation component navigate.js in such way:
<TabNavigation isSignedIn={isSignedIn}/>
Then in my Tab Navigation I recieve data in such way:
export default function TabNavigation({isSignedIn}) {...
Pass it to Stack Screen:
<Tab.Screen name="My Account" children={()=><AccountStackScreen isSignedIn={isSignedIn}/>} options={{
tabBarIcon: () => (<Image source={require("./assets/icon-assets/account.png")} style={{width: 28, height: 28}} />)
}}/>
recive it in Stack Screen:
const AccountStack = createNativeStackNavigator();
function AccountStackScreen({isSignedIn}) {
console.log({isSignedIn}) /// display Object {"isSignedIn": true,}
And finally, when I am trying to pass this object to Account.js component, it become undefined:
return (
<AccountStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: '#FEE6E9',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
color: '#444444',
},
headerBackTitleVisible: false,
headerShadowVisible: false,
}}>
<AccountStack.Screen
name='Account'
component={Account}
options={{title: 'My Account'}}
isSignedIn={{isSignedIn}}
/>
</AccountStack.Navigator>
)
The result of displaing in Account.js component:
export default function Account({isSignedIn}) {
console.log({isSignedIn}) /// display - Object {"isSignedIn": undefined,}
CodePudding user response:
You should pass props while navigating to desired screen or else you can use Context API
For Example: if you want to pass props from Home Screen to Account Screen,
You can use onPress={() => { navigation.navigate('Account', { isSignedIn }); }}
CodePudding user response:
Find a decision in react navigation documentation: https://reactnavigation.org/docs/params/#initial-params
The final decision is looks like (in navigation.js):
<AccountStack.Screen
name='Account'
component={Account}
options={{title: 'My Account'}}
initialParams={{isSignedIn, login}}
/>
Where the main magic in initialParams
And recieve data in component Account.js:
export default function Account({route, navigation}) {...
var data = route.params.isSignedIn;
Where the main magic in route and route.params.isSignedIn