Search code examples
react-nativereact-propsrouteparams

How to pass a prop/value through a component


I am trying to pass a prop from one component to another. I can navigate quite easily to the page, I just cannot pass the prop.

// NewGameScreen.jsx
import { useNavigation, useRoute } from '@react-navigation/native';
const NewGameScreen = () => {

//………………..

    const navigation = useNavigation();
    const figure = 8

    const goToEnteringEmailsScreen = () => {
        console.log("Number:", number);
        navigation.navigate('EnteringEmailsScreen', { figure });
    };

    return (
//……………
    );
};


export default NewGameScreen;

The above is my code to pass the prop. This is the receiving component below :

// EnteringEmailsScreen.jsx
import React from 'react';
import { View, Text } from 'react-native';
import { useRoute } from '@react-navigation/native';

const EnteringEmailsScreen = () => {
    const route = useRoute();
    console.log("Route Params:", route.params);
    const receivedFigure = route.params?.figure;
    console.log("Received figure:", receivedFigure);
    return (
        <View>

            <Text>Received figure: {receivedFigure}</Text>
        </View>
    );
};

export default EnteringEmailsScreen;

I keep getting undefined when I try to console log and capture the prop. Can anyone see what error I am making? The documentation suggests it should be quite simple but it is not working for me.

I have tried the code above in my question, which is using params to try and receive the prop.

Edit: This is my code for the navigation which I have in the main App.js component :

//App.js
//------------
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import NewGameScreen from "./NewGameScreen";
import EnteringEmailsScreen from "./EnteringEmailsScreen";

const Stack = createStackNavigator();

//………….

const EnteringEmailsStack = createStackNavigator();

const EnteringEmails = () => (
  <EnteringEmailsStack.Navigator>
    <EnteringEmailsStack.Screen
      name="NestedEnteringEmailsScreen"
      component={EnteringEmailsScreen}
      options={{ headerShown: false }}
    />
  </EnteringEmailsStack.Navigator>
);

export default function App() {

//…….
  return (
//………
      <NavigationContainer>
        <Stack.Navigator>
//………………………………………..
          <Stack.Screen name="EnteringEmailsScreen" component={EnteringEmails} />
        </Stack.Navigator>
      </NavigationContainer>
  );
}



Solution

  • The reason you are unable to pass the parameter properly is because you passed it to the navigator but didnt pass it to the nested screen. So when navigating to the screen, instead of this implementation

    navigation.navigate('EnteringEmailsScreen', { figure });
    

    try

    navigation.navigate('EnteringEmailsScreen', { screen: 'NestedEnteringEmailsScreen', figure });