GroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupGroupSkip to Content

React Native brings the React paradigm to mobile app development. It’s goal isn’t to write the code once and run it on any platform. The goal is to learn-once (the React way) and write-anywhere. An important distinction to make. This tutorial only covers iOS, but once you’ve learned the concepts here you could port that knowledge into creating an Android app very quickly.

If you have only ever written applications in Swift, you might not be particularly excited about the prospect of using JavaScript. However, the functional programming aspect should pique your interest!

Swift has introduced more functional ways to encode algorithms, as well as techniques that encourage transformation and immutability. However, the way in which you construct your UI is very much the same as it was when developing with Objective-C: it’s still UIKit-based and imperative.

The community has even added tools such as Expo and Create React Native App to help you quickly build React Native apps without having to touch Xcode or Android Studio!

This React Native tutorial takes you through the process of building an iOS app for searching UK property listings:

Don’t worry if you’ve never written any JavaScript or used the CSS-like properties you’ll see. This tutorial will guide you through every step and provide resources where you can learn more.

Navigate to the folder where you would like to develop your app and run the following in Terminal:

react-native init PropertyFinder

This uses the CLI tool to create a starter project containing everything you need to build and run a React Native app.

If you get complaints about the version of node, make sure the one installed by brew is the one in use. Run brew link --overwrite node in the terminal.

In Terminal, run:

cd PropertyFinder

In the created folders and files you will find a few items of note:

node_modules is a folder which contains the React Native framework

index.js is the entry point created by the CLI tool

App.js is the skeletal app created by the CLI tool

ios is a folder containing an Xcode project and the code required to bootstrap
your application

android is a folder containing Android-related code, you won’t be touching those in this tutorial.

Open the PropertyFinder.xcodeproj in the ios folder with Xcode, then build and run. The simulator will start and display the following:

If you encounter a compiler error indicating 'config.h' file not found in the third-party target, you may need to install Glog manually. Try these instructions.

If you see build-time warnings related to updating PropertyFinder project settings, go ahead and make those updates. Ignore warnings related to the other projects.

Many of the warnings may be related to unused parameters. You may also see null pointer logic errors in the yoga library that are actually not errors.

You might also have noticed that a terminal window has popped up, displaying the following:

This is Metro Bundler, the React Native JavaScript bundler running under Node.js. You’ll find out what it does shortly.

Note: If you get an error starting up the packager, then in Terminal run: react-native start

Don’t close the terminal window; just keep it running in the background. If you do close it by mistake, simply stop and re-run the project via Xcode.

Note: You’ll be mostly writing JavaScript code for this React Native tutorial. Instead of using Xcode, I use Sublime Text, which is a cheap and versatile editor, but Atom, Brackets or any other lightweight editor will do the job.

React Native Basics

In this section, you’ll be introduced to React Native basics as you begin working on PropertyFinder.

Open App.js in your text editor of choice and take a look at the structure of the code in the file:

Creates a style object that controls the component’s layout and appearance.

Take a closer look at this import statement:

import React, { Component } from 'react';

This uses the ECMAScript 6 (ES6) import syntax to load the react module and assign it to a variable called React. This is roughly equivalent to linking and importing libraries in Swift. It also uses what’s called a destructuring assignment to bring in the Component object. Destructuring lets you extract multiple object properties and assign them to variables using a single statement.

ES6 is a much nicer way to write JavaScript, supporting features like default parameters, classes, arrow functions, and destructuring assignments. Apple has supported ES6 since iOS 10, but older browsers may not be compatible with it. React Native uses a tool called Babel to automatically translate modern JavaScript into compatible legacy JavaScript where necessary.

Back to App.js, check out the class definition:

export default class App extends Component<{}> {

This defines a class which extends a React Component. The export default class modifier makes the class “public”, allowing it to be used in other files.

App extends React.Component, the basic building block of the React UI. Components contain immutable properties, mutable state variables and expose a method for rendering. Your current application is quite simple and only requires a render method.

React Native components are not UIKit classes; instead they are a lightweight equivalent. The framework takes care of transforming the tree of React components into the required native UI.

This defines a single style that you’ve applied to the description text. If you’ve done any web development before, you’ll probably recognize those property names. The React Native StyleSheet class used to style the application UI is similar to the Cascading Style Sheets (CSS) used on the Web.

Then, get rid of the instructions assignment code block as you no longer need it.

Save your changes to App.js and return to the simulator. Press Cmd+R, and you’ll see your fledgling property search app starting to take shape:

That’s a JavaScript application running in the simulator, rendering a native UI, without a browser in sight!

Still don’t trust me? :] Verify it for yourself: within Xcode, select Debug\View Debugging\Capture View Hierarchy and take a look at the native view hierarchy. You will see no UIWebView instances anywhere! Your text is being displayed in a view called RCTText. But what is that? Back in Xcode select File\Open Quickly… and type in RCTView.h. Notice RCTView inherits directly from UIView. Neat!

Curious as to how it all works? In Xcode open AppDelegate.m and locate application:didFinishLaunchingWithOptions:. This method constructs a RCTRootView, which loads the JavaScript application from the index JavaScript file and renders the resultant view.

The Terminal window that was opened when you ran this application started a packager and server that allows your JavaScript code to be fetched, by default on port 8081. For example:

http://localhost:8081/index.bundle?platform=ios

Open this URL in Safari; you’ll see the JavaScript code for your app. You can find your “Search for houses to buy!” description code embedded among the React Native framework.

When your app starts, this code is loaded and executed by the JavaScriptCore framework. In the case of your application, it loads the App component, then constructs the native UIKit view.

Using JSX

Your current application uses React.createElement to construct the simple UI for your application, which React turns into the native equivalent. While your JavaScript code is perfectly readable in its present form, a more complex UI with nested elements would rapidly become quite a mess.

Make sure the app is still running, then return to your text editor to edit App.js. Modify the body of render to be the following:

This is JSX, or JavaScript syntax extension, which mixes HTML-like syntax directly in your JavaScript code; if you’re already a web developer, this should feel rather familiar. You’ll use JSX throughout this article.

Save your changes to App.js and return to the simulator. Press Cmd+R, and you’ll see your application refresh to display the updated message:

Re-running a React Native application is really as simple as refreshing a web browser! :] Note that this will only reflect changes made to your JavaScript files – native code or resource changes will require a rebuild in Xcode.

You can even skip having to refresh the app by enabling live reload. Press Cmd+D in the simulator then select Enable Live Reload:

This constructs a navigation controller, applies a style and sets the initial route to the SearchPage component. In web development, routing is a technique for defining the navigation structure of an application, where pages — or routes — are mapped to URLs.

Within the same file, add the following to the styles list under the closing brace of the description style:

container: {
flex: 1,
},

This tells the component using this style to fill all available space. This ensures that the component’s children are visible.

Save your changes and check the simulator to see the updated UI:

There’s the navigation controller with its root view, which is currently the search description text. Excellent — you now have the basic navigation structure in place.

Building out the Search Page

Add a new file named SearchPage.js and place it in the same folder as App.js. Add the following code to this file:

Again, these are standard CSS properties. Setting up styles like this is less visual than using Interface Builder, but it’s better than setting view properties one by one in your viewDidLoad() methods! :]

Save your changes.

Open App.js and add the following just after the current import statements near the top of the file:

import SearchPage from './SearchPage';

This imports SearchPage from the file you just created.

Remove the SearchPage class and its associated description style from App.js. You won’t be needing that code any longer. This may also be a good time to get rid of the all unused imports: Platform, Text and View.

Save your changes and return to the simulator to check out the new UI:

Styling with Flexbox

So far, you’ve seen basic CSS properties that deal with margins, paddings and color. However, you might not be familiar with Flexbox, a more recent addition to the CSS specification that’s useful for handling complex layout across different screen sizes.

React Native uses the Yoga library under the hood to drive layout. Yoga is a C implementation of Flexbox and it includes bindings for Swift, Objective-C, Java (for Android), and C# (for .NET).

Generally you use a combination of flexDirection, alignItems, and justifyContent Yoga properties to manage your layout.

So far, your layout has a container with two children arranged vertically:

This is due to the default flexDirection value of column being active. flexDirection helps define the main axis and cross axis. Your container’s main axis is vertical. Its cross axis is, therefore, horizontal.

alignItems determines the placement of children in the cross axis. Your app has set this value to center. This means the children are center-aligned.

You’re going to see some other layout options at play.

Open SearchPage.js and insert the following just after the closing tag of the second Text element:

The text field and Go button are on the same row, so you’ve wrapped them in a container view using the flowRight style which uses flexDirection: 'row' to horizontally place the items in a row.

You’ve also added a flexGrow: 1 style to the text input. Yoga first lays out the text input and button according to their sizes. It then distributes the remaining space according to the flexGrow values. The text input therefore takes over the remaining space.

The basic Button doesn’t provide much UI customization. You could build and customize your own buttons using TouchableOpacity or TouchableHighlight.

Handling Assets

The final step to complete the search screen of the application is to add the house graphic. Download and unzip the images zip file.

Next, create a directory in your root project folder and call it Resources. Place the three images of the house in this directory.

Asset Catalogs: Apple recommends placing images in Asset Catalogs where possible. In React Native, however, it’s recommended not to. Placing your assets alongside your components helps to keep your components self contained, doesn’t require the app to be relaunched if you add new images. It also provides a single place for adding images if you are building for both iOS and Android.

Back in SearchPage.js, add the following beneath the closing tag of the View component that wraps the text input and button:

This sets the TextInput value property — that is, the text displayed to the user — to the current value of the searchString state variable. This takes care of setting the initial state, but what happens when the user edits this text?

The first step is to create a method that acts as an event handler. Within the SearchPage class add the following method below the constructor:

The function takes the value from the native browser event’s text property and uses it to update the component’s state. It also adds some logging code that will make sense shortly.

Note: JavaScript classes do not have access modifiers, so they have no concept of private. As a result you often see developers prefixing methods with an underscore to indicate that they should be considered private.

To wire up this method so it gets called when the text changes, return to the TextInput field within the render method and add an onChange property so the tag looks like the following:

Looking at the console logs, the order of the logging statement seems a little odd:

This is the initial call to render() to set up the view.

You invoke _onSearchTextChanged() when the text changes.

You call this.setState() to schedule an update to the component state to reflect the new input text. This triggers another render.

You log the current and the next search text values.

Note: You may see frequent log messages related to nw_connection_get_connected_socket or finished with error - code : -1001. These are due to attempted connections to the React debugging tools. Silence these temporarily by going to Product \ Scheme \ Edit Scheme and finding the Arguments tab of the Run config. Add a new environment variable called OS_ACTIVITY_MODE with the value disable.

Build and run the project for the settings to take effect.

A React component state change triggers a UI update. This de-couples the rendering logic from state changes affecting the UI. Most other UI frameworks put the onus on you to update the UI based on state changes. Alternatively, the updates are done through an implicit link between the state and UI. For an example of the latter, see this article on implementing the MVVM pattern with ReactiveCocoa.

At this point you’ve probably spotted a fundamental flaw in this concept. Yes, that’s right — performance!

Surely you can’t just throw away your entire UI and re-build it every time something changes? This is where React gets really smart.

Each time the UI renders itself, it takes the view tree returned by your render methods, and reconciles — or diffs — it with the current UIKit view. The output of this reconciliation process is a simple list of updates that React needs to apply to the current view. That means only the things that have actually changed will re-render!

You can wrap your head around all that later; you still have some work to do in the app.

Initiating a Search

First, remove the logging code you just added above, since it’s no longer necessary.

In order to implement the search functionality you need to handle the Go button press, create a suitable API request, and provide a visual indication that a query is in progress.

Within SearchPage.js, update the initial state within the constructor:

this.state = {
searchString: 'london',
isLoading: false,
};

The new isLoading property will keep track of whether a query is in progress.

This is a ternary if statement that optionally adds an activity indicator, depending on the component’s isLoading state. Because the entire component is rendered each time, you are free to mix JSX and JavaScript logic.

Within the JSX that defines the search UI in return, add the following line below the Image to place the spinner:

urlForQueryAndPage doesn’t depend on SearchPage, so it’s implemented as a free function rather than a method. It first creates the query string based on the parameters in data. Then it transforms the data into name=value pairs separated by ampersands. Finally, it calls the Nestoria API to return the property listings.

Save your changes, head back to the simulator and press Go. You’ll see the activity indicator spin:

This makes use of the fetch function, which is part of the Fetch API. The asynchronous response is returned as a Promise. The success path calls _handleResponse which you’ll define next, to parse the JSON response.

This navigates to your newly added SearchResults component and passes in the listings from the API request. Using the push method ensures the search results are pushed onto the navigation stack, which means you’ll get a Back button to return to the root.

Save your changes, head back to the simulator and press Go. You’ll be greeted by a list of properties:

It’s great to see the property listings, but that list is a little drab. Time to liven things up a bit.

This manipulates the returned price, which is in the format 300,000 GBP, to remove the GBP suffix. Then it renders the row UI using techniques that you are by now quite familiar with. Of note, an Image is added to the row and is loaded from a returned URL (item.img_url) which React Native decodes off the main thread.

You may have noticed that this component extends React.PureComponent. React re-renders a Component if its props or state changes. React only re-renders a PureComponent if a shallow compare of the state and props shows changes. Used under the right conditions, this can give your app a performance boost.

If you’re a web developer, you’ve seen how to use JavaScript to easily create a native app. If you’re a native app developer, you’ve gained some appreciation for React Native’s fast iteration cycle. Whether you decide to use React Native in a future app or simply stick with Swift, I hope you’ve learned some interesting principles to apply to your next project.

If you have any questions or comments on this React Native tutorial, feel free to join the discussion in the forums below!