Setting up navigation
So far our app is pretty functional, but contains only one screen, so we will now set up multiple screens via React Navigation. There are a couple of React Native libraries for navigation but here we find ourselves limited: in order to keep the screens performant the navigation implementation must be written in native code. (As a matter of fact, React Navigation just added support for macOS some months ago.)
It's not perfect - for example animations are not supported - so unlike the iOS and Android counterparts, our app won't be that pretty. However I expect the situation to improve with time.
Installing React Navigation#
In order to get React Navigation working we will need to add some dependencies to our project:
After adding our dependencies, navigate to the macOS folder and do a
Sometimes you might face some issues such as the packager having cached outdated files, and in this case the best you can do is kill the packager and start it again (it will have opened in a new terminal window, and you can just close it). If that still does not solve your problem, running our helper command
yarn nuke and compiling the app again should clear any outdated caches.
Setting up a router#
Navigation in React Native is based on navigators. We have installed a stack navigator but there are others like a bottom tab navigator or a side menu navigator (not all might support macOS). You can compose these navigators as you see fit for your app.
We will start by setting up a simple stack navigator, just to get your foot in the door.
src folder create a
Routes.tsx file. In previous lessons we abstracted our Books into a
container component, in this Routes file, this is where we will use our containers. As a rule of thumb, only containers should be registered as the navigable routes.
Besides importing React, we will import the
createStackNavigator function from react-navigation. We will also import our styling functions to customize the header element of the navigation (react-navigation/stacks inserts headers by default on the screens).
You can see we have created a
RootStack. This will be the root stack navigator of our app, but you could switch this with any other navigator (react-navigation offers a variety of them). A Stack navigator simply will stack the screens so you can navigate backwards by popping elements off the stack.