Getting started with React Navigation

Broonix August 20, 2017
Source
I recently had some time to try React Navigation. It's a very nice routing solution to use in your React Native applications. Let's walkthrough a simple example of using React Navigation in a project. Project Setup We will use create-react-native-app for this demo. Ensure you have it installed via npm install -g create-react-native-app. We will start by creating a new project: [Code block] If you run yarn run ios you'll see a simple single page demo application. Adding React Navigation We will install React Navigation using yarkpkg: [Code block] Adding Screens React Navigation lets us easily route from one screen to an other. So let's start by creating a few simple screens to start. [Embedded code (GitHub Gist)] In the example above we create three components that render a view. Each of these will become a screen in our app that we can navigate to. Creating a navigator We will use a StackNavigator for this example. [Embedded code (GitHub Gist)] Above we create a StackNavigator with three screens. We provide it some coloring and a default title. I'll elaborate a bit more on styling the navigation bar later in this article. If you load up the app you should now see Screen1 with a navigation bar. [Embedded code playground] Well, we are 1/2 there already. We now need to add some navigation so we can move between screens. Navigating Now we will expand Screen 1 so we can click a button to navigate to Screen2 or Screen2. [Embedded code (GitHub Gist)] As you can see we are binding the onPress event to navigate to the other screens in our app. Note: this.props.navigation is not available to the child components on a given screen. You'll need to pass it down to the child components if you want to navigate from them. Styling React Navigation Here are what all style related properties I passed into the StackNavigator do: [Code block] Completed Demo And here you have it. A rather simple example of how to get started using React Navigation in a React Native project. [Embedded code playground] If you want to check out this code and run it locally, I've also uploaded this demo to GitHub: https://github.com/brookslyrette/ReactNavigationDemo Read the original post with all embeds and interactive content at https://rants.broonix.ca/getting-started-with-react-navigation/

Discussion in the ATmosphere

Loading comments...