Random UTF-8 characters


20 Aug 2017 in reactreact-nativereact-navigationcoding

Getting started with React Navigation

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:

$ create-react-native-app ReactNavigationDemo
# cd ReactNavigationDemo

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:

$ yarnpkg add react-navigation

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.

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.

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.

Well, we are 1/2 there already. We now need to add some navigation so we can move between screens.

Now we will expand Screen 1 so we can click a button to navigate to Screen2 or Screen2.

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:

navigationOptions: {
  headerTitle: 'Default App Title', // Title shown when a screen does not have a title
  headerTitleStyle: {
    color: '#FFF' // Color of the text in the header
  headerStyle: {
    backgroundColor: '#f57c00' // Background color for bar
  headerBackTitle: null, // Text for 'back' button. `null` sets this to an empty string
  headerTintColor: '#FFF', // Color of the text used in the back button/icons

Completed Demo

And here you have it. A rather simple example of how to get started using React Navigation in a React Native project.

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