Adding a simple navigation system to React Native – Part II

In my last post, I started the process of adding a navigation system to my app. The idea is to make it easy for the developer to add more pages to the app, and easy for the user to move around from page to page. I’m using the React Navigation community project. I’ve got the right packages installed and imported into my app. It’s clear to me from the documentation that I need to add a new component as a new page.

So I add a rudimentary, blank component. I’ve decided that this page will show a map of the theater that the user picks on the first page, so I name the file MapsScreen.js, with this source:

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class MapsScreen extends Component {
    render() {
        return (<View style={[{ flex: 1, justifyContent: 'center' },
        { flexDirection: 'row', justifyContent: 'space-around', padding: 10 }]}>
            <Text>A map goes here</Text>
        </View>);
    }
}

Then I edit App.js to include a route to this component. It looks like this:

import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import MoviesScreen from './MoviesScreen';
import MapsScreen from './MapsScreen';

const MainNavigator = createStackNavigator({
    Movies: { screen: MoviesScreen },
    Maps: { screen: MapsScreen }
});

const App = createAppContainer(MainNavigator);

export default App;

It was more trouble than I’d like to add the React Navigation packages, but now that they’re in place, it’s super easy to add a new page. According to the documentation, I just need to call a function called navigate in order for a button click to take me to a new page.

I’ve already attached a method handleShowTheaterClick to my “GO” button. Here’s the short navigation code that needs to be added:

handleShowTheaterClick() {
    const { navigate } = this.props.navigation;
    navigate('Maps', {});
}

This is all it takes to make the “GO” button functional. I click the button, and I’m taken to my “Maps” screen, which looks like this:

current app functionality selecting movie and theater

Notice there’s a back arrow in the title bar. I can click that to get back to the previous screen. I hardly needed to do any work at all to get built-in navigation functionality. This is the beauty of code reuse.

The source code for this example – App.js, MoviesScreen.js, and MapsScreen.js – is available online.

If you found this interesting, click the subscribe button below! I write a new post about once a week.

Leave a Reply

Your email address will not be published. Required fields are marked *