Search code examples
javascriptreactjsreact-nativereact-navigationreact-navigation-v5

In React Native Navigation, how do I send props to my screens?


I want to be able to use navigation on a different screen other than just the first one but I am getting an error that this.props does not exist.

I have my App.js file setup like this:

import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';

import Screen2 from './screens/Screen2';  
import Screen3 from './screens/Screen3';
import HomeScreen from './screens/HomeScreen';

const Stack = createStackNavigator();

function HomeScreen({ navigation }) {
  return (
    <View>
        <Button
        title="Go to Screen2"
        onPress={() => {
        navigation.navigate('Screen2');
        }}
      />
      <Button
        title="Go to Screen3"
        onPress={() => {
        navigation.navigate('Screen3');
        }}
      />
    </View>
  );


const App: () => React$Node = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Screen2" component={Screen2} />
        <Stack.Screen name="Screen3" component={Screen3} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

The buttons in app.js work but if I go to Screen2 and click a button that intends to go to another (Screen3 in the example below), props does not exist.

Example Screen2.js would look like this:

const Screen2: () => React$Node = () => {

  return (
    <>   
      <View style={{ flex: 1 }}>
        <Button
        title="Go to Screen3"
        onPress={goToScreen3}}
      />
      </View>     
    </>
  );

function goToScreen3() {
  if(condition){
this.props.navigate.navigate('Screen3');
}}

How do I pass the props so that I can use navigation in my second screen?


Solution

  • For functional component sometimes it's tricky to pass navigation through props as well. So just use withNavigation.

    you have to import it and wrap the function with it.

    import { withNavigation } from 'react-navigation';
    
    const Screen2 = props => {
    
      const goToScreen3 = () => {
        if(condition){
        props.navigate.navigate('Screen3');
      }}
    
      return (
        <>   
          <View style={{ flex: 1 }}>
            <Button
            title="Go to Screen3"
            onPress={goToScreen3()}
          />
          </View>     
        </>
      );
    
    
    
    export default withNavigation(Screen2)