1. 17
    Show a New Screen with React Navigation and StackNavigator
    2m 52s

Show a New Screen with React Navigation and StackNavigator

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

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.

Instructor: [00:00] Install React Navigation with npm install --save react-navigation, which we'll use to add navigation to the app. In App.js, import { createStackNavigator } from 'react-navigation' and use it to make and export a new stack navigator.

[00:25] We want the first screen in the stack to be the lists screen, which is currently being exported as default. Let's move that to a new file called restaurantList.js. We'll put it in components. Be sure to move the appropriate import statements as well. We can significantly clean up App.js.

[00:56] Then we can import the new list file and use it to define the first screen in the stack navigator, which we'll call home. When we reload now, we still see the list, but we have the addition of a navigation header bar, which is how we know this is properly in a stack navigator.

[01:22] Let's start the debugger in the render() method to look at what props React Navigation gives us. Because the restaurantList is in the stack navigator, we get the navigation prop. Inside of there, we have a navigate function, which we can use to navigate to another screen in the stack navigator.

[01:40] Remove the debugger from the list and make a new screen called restaurantInfo.js, which we'll leave as a simple React Native view and a text label for now. Then, in App.js, we can import that new info screen and put it in our stack navigator. Note that the component is called restaurantInfo, but we're just naming the screen info, which is the name that we'll use when navigating.

[02:08] If we reload now, the info screen is on the stack, but we need to expressly navigate to see it. Let's make these info buttons navigate to that screen instead of popping up in place.

[02:20] In restaurantList.js, we have to pass the navigation prop to each restaurant row because that's where the onPress for those info buttons are. In restaurant row, we can change the info pressed function to call this.props.navigation.navigate and pass an info, which is the name of the key for the screen in our stack navigator that we want to show.

[02:44] When we reload, the info buttons now push a new screen onto the stack navigator, and we can navigate back and forth.