9

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 } ?

Questions123
  • 372
  • 2
  • 6
  • 18

2 Answers2

18

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

You can access it like below

this.props.navigation.navigate('nextScreen')
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50
-1

1 : import { Link, withRouter } from 'react-router-dom';

2 : export default withRouter(Component);

Login = () => {
  this.props.history.push("/login")
}
Krunal Vaghela
  • 1,007
  • 2
  • 12
  • 22