Show a New Screen with React Navigation and StackNavigator
Navigation is not built in to React Native, so we’ll use the React Navigation library to set up a navigator for our application. We’ll start with a Stack Navigator, which allows us to “push” new screens onto the stack, and gives us a nice “back” button to go back to the previous screen.
Navigation
❗Note: This course uses react-navigation version 2. The current version is 5 and contains a slightly different API. The concepts of stack and tab navigation are the same, so for consistency with the videos install version 2, and use the corresponding docs
🤔React Navigation can be used to navigate between different pages or screens in the application.
npm i react-navigation@^2.0.0
There are two main types of navigation we can use:
🤔Stack 🥞- you can imagine this is like a stack of pancakes, where the top pancake - current screen - is the one you are focusing on eating - or just looking at ... don't eat your phone!. You decide the blueberry pancake sounds even tastier so you order it and the chef places it ontop of the stack, so now you are focused on the blueberry pancake. When you finish the blueberry pancake you are back to the pancake that came before it. This is how stack navigation works, until you are back to the root pancake - and then you order some more!
🤔Tab 🍴- this is the navigation that sits at the bottom of screen, and is usually available across all screens. You can think of this as your knife and fork. You can use your knife and fork no matter which pancake you are currently eating.
import { createStackNavigator } from 'react-navigation'import RestaurantList from 'components/RestaurantList'import RestaurantInfo from 'components/RestaurantInfo'...createStackNavigator({Home: { screen: RestaurantList },Info: { screen: RestaurantInfo }})
The navigate() function allows navigation to any other screen. This is automically passed down as a prop to the top level component rendered by a stack or tab navigator.
this.props.navigation.navigate('Info')
As this is only passed to the top-level component, if any children need to be able to navigate, they will need to be passed the function as a prop.
<ChildComponent navigate={this.props.navigation.navigate} />