React Native Stack Navigation With Class Component

11,236

You dont have to pass navigation, its passed as a prop.

You can access it like below

this.props.navigation.navigate('nextScreen')
Share:
11,236
Questions123
Author by

Questions123

Updated on June 07, 2022

Comments

  • Questions123
    Questions123 almost 2 years

    I am currently building a react native app and am using a stack navigator to navigate between the screens in my app. In my App.js, I am currently storing the screens in this format:

    const Stack = createStackNavigator();
    
    export default function App() {
      return (
          <NavigationContainer>
            <Stack.Navigator initialRouteName="screen1">
              <Stack.Screen name="screen1" component={Screen1}></Stack.Screen>
              <Stack.Screen name="screen2" component={Screen2}></Stack.Screen>
            </Stack.Navigator>
          </NavigationContainer>
      );
    }
    

    After the user is in screen 1, I want to be able to navigate to screen 2 on the press of a button. I read through the documentation and I only saw examples on how to do this with functional components, for example:

    function Screen1({ navigation }) {
      return (
        <View>
          <Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
        </View>
      );
    }
    

    But how can I do this with a class component:

    class Screen1 extends Component {
    
        render() {
            return(
                <View>
                   // This does not work because I do not know how to pass in the navigation object
                   <Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
                </View>
            )
        }
    }
    

    Where do I pass in the { navigation } ?