React Native: How To Navigate Between Screens

Installing React Navigation On Expo

The first step in this process is to install react-navigation/native to allow us to import a NavigationContainer into our project. In this same step we will also be installing react-navigation/stack in order to allow us to import createStackNavigator. With your app NOT running within terminal enter:

npm add @react-navigation/native @react-navigation/stack
expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view

Configuring React Navigation

I’d like to take a second before we continue to go over file structure. Because I have certain preferences on how I setup my react app, my file structure may look a bit different than yours. Feel free to setup your app to mirror mine if you’d like, but I figured I should mention how I like to setup mine due to some of the relative paths I’m going to use in the following example. I should also mention I generally make an App folder I keep everything in. Here is a pic of my basic setup:

The highlighted component index.js is at the topmost layer of this app. I am also hovering my cursor over Navigation.js because we will be doing some work in this as well.
In this example the two screens we will navigate between are Home and Options
In this example I’ve disabled the headers because it is my personal preference. Feel free to leave them and see what it looks like on the various screens if you’d like.
default export of Navigation.js

Implementing React Navigation

Within the top layer of our app (in this examples case index.js) we need to import our new Navigation component and render it. Like so:

the highlighted portions are the aforementioned navigation prop. Once this Text is touched or clicked, the app will navigate to the Options screen.
This will render some centered text reading “Go back to Home Screen” that once clicked/touched will navigate the app back to the Home screen. Again the onPress function with navigation is highlighted.

Conclusion

The ability to navigate between screens is essential for any React Native app. It is important to note that onPress can be used with a number of different context (not just text) such as on images or buttons etc. In this way there are many different options available to link your screens together. This article just sought to focus on a very basic example. I hope you enjoyed it and happy coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store