Written by Alex Gibson, on April 13, 2017


Setting up an iOS Project to add React Native can be a pain.  The documentation seems limited as cocoapods is the preferred method of installation but the pod file has to point to the javascript directory.  This was not intuitive for me at first.  This tutorial is how to quickly get up and running with React Native inside a native iOS application. I am assuming you have at least played with React Native and that you have installed the needed sdks.  You will also need cocoapods installed as this is the recommended approach to install react native in your iOS App.  I would also recommend Visual Studio Code by Microsoft to edit your files on the React Native side of the code.  VSC has some great plugins to help with code completion and snippets so look through the plugins you can install as well. Walking through the tutorials provided by Facebook in the Tutorials are great.

So let’s get to the task at hand and create a new project and name it iOSWithReactNative.  Let Xcode create the files and then close the project.  Rename the top level folder iOS.

 

Now create a empty folder and name it anything you want as the naming here is not that important.  I am sticking with the original name of iOSWithReactNative.  Drag the iOS project into this folder and your structure should look like this.  This folder will serve as the container for both our native iOS code/App and the javascript code needed for React Native.

 

Now we need to create another folder inside named js.  This will stand for javascript.

 

Now we have the folder structure in place let’s get React Native installed.  The easiest way to do this is to open the js folder and create a new file here.  The js folder is empty but not for long. Use your favorite editor, mine in this case is Visual Studio code, and create our first javascript file. I choose new file from the top menu.

 


{
    "name": "iOSWithReactNative",
    "version": "1.0.0",
    "private": true,
    "description": "iOS with React Native views",
    "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
    },
    "dependencies": {
    "react": "~15.4.2",
    "react-native": "~0.42.3"
    }
}

 

Name the file package.json and save it to the js folder.  So what is going on here?  Well think of this kind of like a pod file.  This will tell the npm command to install React and React Native.  Open terminal at the folder js and run


npm install

You should see action and the files being installed to the js folder.  Open the js folder and make sure it looks like this.

So we now have to get the files into Xcode.  The recommended approach according to the docs is with cocoapods.  Open a terminal window on the folder iOS that is inside the container folder iOSWithReactNative.  Run the command


pod init

Once this is complete open up the iOS folder and find the podfile.  Open the podfile and make sure you add the needed lines for React Native.  My podfile now looks like below.


# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'iOSWithReactNative' do
 use_frameworks!

  # Pods for iOSWithReactNative
pod "Yoga", :path => '../js/node_modules/react-native/ReactCommon/yoga'
pod 'React', :path => '../js/node_modules/react-native', :subspecs => [
  'Core',
  'RCTImage',
  'RCTNetwork',
  'RCTText',
  'RCTWebSocket',
]

end

You can see from the pod file that we are installing the files from the js folder into our project with cocoapods.  This is why the folder structure is important and we named the js folder the way we did.  If you named your folder differently change the path in the podfile.  Save the file and open a terminal window on the iOS folder.  Run pod install and you should see the needed files installed into the iOS project folder.  We should be good to go so let’s run some tests to make sure.

Open the workspace in the iOS folder.  I always like to run the application after installing new things so that Xcode knows that the files are there.  Give the project a run then go to the ViewController file and import React just under the import for UIKit.


import React

Now the way React Native works is by loading the code over http when we are developing so we need to allow our iOS application to load the files and since NSAppTransportSecurity will stop us we need to add some keys or our info.plist.  Open the info.plist as source code by right clicking and choosing open as source and add these keys.  In a live application this can be removed as you can include the js file in the main bundle.


<key>NSExceptionDomains</key>
  <dict>
  <key>localhost</key>
  <dict>
  <key>NSExceptionAllowsInsecureHTTPLoads</key>
  <true/>
  </dict>
  </dict>

So this allows our application to load the js files over the local host. Now use Visual Studio Code and open the entire js folder of our project.  If you played with React Native a bit before starting this tutorial this will not seem so confusing or scary.  All React Native code has to start from an index file.  Since we are using iOS it will be specifically called index.ios.js. So create a new file that will be our index file and let’s create our first view and name the file index.ios.js.  In the file we import the needed React Native components and return and render the view.


'use strict';
import {
 AppRegistry,
 StyleSheet,
 Text,
 View
} from 'react-native';
import React, { Component } from 'react';

export default class RNView extends Component {
 render() {
 return(
    <View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
        <Text>HELLO FROM REACT NATIVE</Text> 
        </View>
   )
  }
}
AppRegistry.registerComponent('RNView', ()=> RNView);

 

Be sure to save the file with Command-S.  All we need to do now is make sure everything is working.  Open a terminal window on the js folder and type


npm start

You should see the server start up in terminal.  Go to the iOS workspace and open the ViewController file and at the top declare a variable for our react native view.


var reactView : RCTRootView!

In the viewDidLoad function add the reactView to the main view.

 


override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        reactView = RCTRootView(
            bundleURL: URL(string: "http://localhost:8081/index.ios.bundle?platform=ios"),
            moduleName: "RNView",
            initialProperties: nil,
            launchOptions: nil)
        reactView.frame = self.view.bounds
        reactView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        self.view.addSubview(reactView)
    }

 

As long as you have the development server running you should be good to go so run the app and you should see your new view from the world of React Native.

 

 

Some tips from here would be that you can go to the simulator menu and shake to enable hot reloading that will allow you to style the view in real time very quickly.  Also, on a real device you may need to replace localhost with your computers address on the network.  Good luck and happy coding.

Check out the tutorial on adding a react native camera to a native app and learn how to pass props and calls functions.  This basic setup will work and we will use it in many tutorials in the future