React Native in an Existing iOS App: Dynamic Routing.

This guide is Part Two in our four-part series Using React Native in an Existing iOS App. Click here for Part One: Getting Started.

Now that we have the ability to use a React Native View anywhere in our app, we need to be able to render different views for different use cases. In other words, we need a router. For this we’ll use the <Navigator /> component provided by RN.

Originally our two native buttons rendered the same RN View. Now we’re going to alter these button actions to route to two different views by passing the route name to our RCTRootView.

React View 1 (Obj C View) renders our content and a background color changing component.

React View 2 (Swift) simply renders the content.

You can find all of the code here on Github:

File Structure

Let’s have a look at the file structure for our ReactComponents folder:

├── Components
│ └── ChangeBackground.js
├── Views
│ ├── ObjectiveCView.js
│ └── SwiftView.js
├── index.ios.js
├── node_modules
│ └── react-native
└── package.json

The Views folder contains any components that the router will render. The Components folder contains any child components needed by the Views.

The Router

The first thing we need to define is the RouteStack. This maps each route name to the view component that should be rendered. Following the documentation we need a renderScene method and an initialRoute object. In the renderScene method we’ll pass our props to the view component so it has access to data passed from Objective C or Swift. We’ll also pass a reference to the <Navigator /> itself so the view component can push more views on the stack, but we won’t be doing that here.

UIViewController Changes

We just need to make a small change to our ReactNativeViewController (from Part 1) to pass the route name to data. We’ll add a public property called route so we can pass a route from anywhere in our app.

Objective C:


Now we can set the route for our respective button click events.

And that’s it!

Dynamic routing using the <Navigator/>. Delivered.

Up next, we’ll talk about using Codepush to push instant app updates. Stay tuned!

If you have any questions or comments, feel free to reach out to us on Twitter at Jesse Sessler and Bruno Barbieri and on Discord at jemise111 and brunobar79.