Home > Net >  Passsing props from App.js to Stack.Screen React Native
Passsing props from App.js to Stack.Screen React Native

Time:01-24

I'm again asking a question regarding ReactNative: I have the following App.js:

export default function App() {

  function Tabs() {
    return <TabBar />;
  }

  const styles = StyleSheet.create({
    backButton: {
      color: global.GUI.ORANGE,
    },
  });

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Tabs"
          component={Tabs}
          ..
        />
        <Stack.Screen
          name="Impostazioni"
          component={Settings}
          ...
        />
        <Stack.Screen
          name="Registrati"
          component={Signup}
         ...
        />
        <Stack.Screen
          name="Login"
          component={Login}
          ...
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

I want to pass to each component some values declared in App.js,but doing something like:

            <Stack.Screen
              name="Impostazioni"
              component={Settings}
              currentUser={"name":"test"}
            />

Return undefined in:

import React from 'react';
import {View,Text} from 'react-native';

const Settings = (props) => {
  --> console.log(props.currentUser) // here is undefined
  return (
    <View >
     <Text>This is Settings!</Text>
    </View>
  );
};

export default Settings

So, how can I correctly pass props to App.js to all other components?

Thanks

CodePudding user response:

You have to either use React Context(recommended) or pass props to your component.

https://wix.github.io/react-native-navigation/docs/third-party-react-context/

Another way:

<Stack.Navigator initialRouteName="LoginScreen" headerMode="none">
 <Stack.Screen name="LoginScreen" component={LoginScreen} initialParams={{'key':'value'}} />
 <Stack.Screen name="CodeVerificationScreen" component={CodeVerificationScreen} initialParams={{'key':'value'}} />
</Stack.Navigator>

You can receive initial params in login.js

console.log(this.props.route.params.key)

Another approach:

Pass props to component - Documentation link:(Please check for your nav version) https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props

  •  Tags:  
  • Related