In plain React, there is no concept of rendering different pages. It only renders the default entrypoint, which is just a single React component. This also applies to Expo and React Native. Everything in your app has to be handled within that single component. Managing transitions between multiple screens can be a complex task. Luckily, react-navigation
can do most of the heavy lifting for us. We can implement the common mobile navigation patterns and connect the screens together.
One of the core principles of react-navigation
is the navigator. It’s the fundamental structure that holds multiple screens of your app. The navigator determines what screen should render and how transitions between multiple screens are animated. All of the screens are identified and referred to by a unique name.
react-navigation
ships with a couple of different navigators, each following one of the navigational patterns you saw earlier:
- Tab Navigator - Renders a tab menu where users can switch between multiple screens. These screens are only rendered when navigated to.
- Stack Navigator - Renders a header with the screen title and optional back buttons when users navigate other screens.
- Drawer Navigator - Renders a sidebar list menu where users can switch between multiple screens. Users can open the menu by swiping from the side of the screen.
Instructions
Before we can define our screens, we have to set up the react-navigation
library. To do this, we have to implement the NavigationContainer
component. This component is responsible for managing the app’s navigation state and makes sure the navigators in your app can function.
Wrap the current App
children with the NavigationContainer
from @react-navigation/native
.
Great! Now that we have the navigation container in place, we can define our basic navigational structure. To refactor our app into screens, we have to define the current App
content as a screen. Let’s use the stack navigator for this single screen to get familiar with the concept of navigators.
Navigators in react-navigation
are created by a factory method. The stack navigator is created by the createStackNavigator
. This method returns an object with a Navigator
and Screen
property. These properties are unique components that you have to use when rendering the screens.
const Stack = createStackNavigator(); <Stack.Navigator> <Stack.Screen name="MyScreen" component={MyScreen} /> </Stack.Navigator>
Move our View
and the Text
component from App
to a custom component called FeedScreen
. This was the first screen users would see in the Codecademy Go app, after login. Add this component to the stack navigator as a screen and set the name of the screen to Feed
.
Awesome! We now have a basic navigational structure. This structure doesn’t match the Codecademy Go app yet. In the next exercise, we will implement a tab navigator to add the Catalog
and other screens.
Run the code one more time to complete this exercise.