Chapter    2

The Simplest Program: Hello World with React Native

“Big things have small beginnings.”

—Prometheus

In the last chapter, you got a good overview of the React ecosystem. Now it’s time to get your hands dirty with React Native. In this chapter, you will set up your environment by installing the prerequisites and then you will create your first React Native application.

The best way to learn is through practical examples. Continuing this theme throughout the book, you will follow examples to learn React Native by programming to understand the concepts.

In this chapter, you will explore the following topics:

  • An introduction to React Native
  • The essentials of React Native
  • The installation of React Native
  • Your first application
  • The anatomy of a React Native application
  • How to debug your application

Note  You might face a situation where different projects work on different Node versions. Therefore, it’s recommended you install NVM (node version manager) to help keep multiple node versions that can be switched between projects.

What Is React Native?

React Native is an open source platform for developing native mobile applications; it was developed largely by a team at Facebook. The cool part of working with React Native is that your program uses standard web technologies like JavaScript (JSX), CSS, and HTML, yet your application is fully native. In other words, your application is blazing fast and smooth, and it is equivalent to any native application built using traditional iOS technologies like Objective-C and Swift. However, React Native does not compromise in terms of performance and overall experience, like popular hybrid frameworks that use web technologies to build iOS apps.

React Native aims to bring the power of React, which was explained in Chapter 1, to mobile development. In the words of the React team, “learn once, write anywhere.” Working with React and React Native, you will see how many of your components built for the Web using React can be easily ported to your React Native iOS apps with little or no modification. React Native introduces a highly functional approach to constructing user interfaces, which is very different from the traditional iOS development approach.

Although React Native was built by Facebook developers, it’s an open source project. The code is available at https://github.com/facebook/reactreact-native.

React Native Prerequisites

Before starting the installation, let’s first review the prerequisites for React Native:

  • iOS apps can be developed only on an Apple Mac with OSX installed. You need OSX version 10.10 or above.
  • You need Xcode 6 or above, which includes the iOS SDK and simulators. React Native only supports iOS7 or above. Xcode can be downloaded from the Apple App Store.
  • It’s helpful if you are enrolled in the Apple iOS Developer program. If you’re not in the iOS Developer Program, you won’t be able to
    • Test applications on actual devices.
    • Access beta OS releases.
    • Test flight for beta testing.
    • Submit your app to the App Store.

Installation

Let’s do a quick, one-time setup of React Native. React Native is an assortment of JavaScript and Objective-C code, so you need tools that create, run, and debug your native application written in JavaScript. Let’s go one by one.

Installing Node and npm

Node.js is an open source platform built on Chrome’s JavaScript runtime; it offers a way to easily build fast, scalable programs. Node.js allows you to run JavaScript in Terminal, and helps create modules. You install Node.js by running the following command in Terminal: $brew install node.

Homebrew is the recommended way to install Node. You can also download the installer from https://nodejs.org and install it manually.

npm is the package manager for Node.js. If you’re from the iOS world, it’s similar to CocoaPods.

Check your Node installation by running the following command in Terminal:

>> node –v
v4.2.1

>> npm –v
2.13.1

Installing Watchman

Watchman observes your files and records when they change. It can also trigger actions (such as rebuilding assets) when matching files change. For more details, visit https://facebook.github.io/watchman/.

You can install Watchman by running the following command:

$brew install watchman

Installing the React Native Package

React Native comes as an npm package, so use the following code to install the React Native-cli module:

npm install -g react-native-cli

Updating React Native

Both React Native and iOS are fast-moving frameworks. It is recommended to update them every time a new release is available. Upgrading React Native is simple. Run the following command in Terminal:

npm update -g react-native-cli

Your First App

Now that you are all charged up about React Native and have your system set up, it’s time to create your first application. To keep things simple, in the beginning just follow along. Sometimes you might feel disconnected by monotonously typing in the code, but going along is enough for now. Remember that mimicry is a powerful form of learning; it’s how we learned most of our skills, such as talking, reading, writing, and it is how you will learn to program with React Native. As you proceed, this method will help you understand deeply why you authored certain pieces of code.

Throughout the book, you will create one application and take it from just Hello World to a full-blown, distribution-level application, except in some places where we need to digress to explore a concept independently. So before you set it up, let’s talk about the problem you plan to solve. The app you will create during the course of this book plans to solve a few housing problems; it will be a very primitive version of any popular property search application.

Let’s call it HouseShare. It will have some rudimentary features like listings, creating an entry, geolocating a property, and many more. As you move along, you will see how various React Native features fit with your application.

That’s quite a lot, but in this chapter you will just create the basic structure for your project using React Native and some Hello World code.

Creating a Basic Skelton

Fire up Terminal and type in the following command:

react-native init HouseShare

This code uses the CLI tool to construct a React Native project that is ready to build and run as-is. This command creates the basic folder structure for your React Native iOS project. Next, let’s get into this directory:

> cd HouseShare/ios/

Now, click HouseShare.xcodeproj. This is an Xcode project file and will open up your project in Xcode. Next, let’s load your application in the iOS simulator. To build your application and load it in the simulator, simply click the Run button at the top (Figure 2-1) or execute Command + R. This will compile, build, and fire up your project in the iOS simulator (Figure 2-2).

9781484213964_Fig02-01.jpg

Figure 2-1. Building by clicking the Run button

9781484213964_Fig02-02.jpg

Figure 2-2. Using the iOS simulator

That was really quick. Thanks to a single command, the basic structure of your project is in place and your application is loaded in the simulator. Also note that Terminal is opened automatically when you run the application from Xcode. This is the Node package manager for React Native. If you kill this, the app will stop working.

Terminal is opened to start the React Native Packager and a server to handle the above request (Figure 2-3). The React Native Packager is responsible for reading and building the JSX (you’ll look at this later) and JavaScript code.

http://localhost:8081/index.ios.bundle

9781484213964_Fig02-03.jpg

Figure 2-3. The packager is ready

Note  If Terminal is not started and the iPhone shows a red screen, run npm start and keep Terminal open.

Set up your project in any editor you prefer. React Native does not force you nor does it have a preference towards any specific editor, so you may continue to use Xcode as default. However, we recommend you open your project in an editor like our personal favorite, Sublime Text.

Make some changes in index.io.js. In fact, remove all code from the file. Now, add the following code:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var HelloWorld = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
         HelloWorld !!
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  welcome: {
    fontSize: 25,
    textAlign: 'center'
  }
});

AppRegistry.registerComponent('HouseShare', () => HelloWorld);

Press Command + R in the iOS simulator and it will refresh the screen, as shown in Figure 2-4. (Note that in this book, we will use the Command key instead of the CMD key, which is equivalent.)

9781484213964_Fig02-04.jpg

Figure 2-4. The screen is refreshed

That was quick! In a fraction of a second you can see the changes you applied. You don’t need to compile the code and restart the simulator for React Native changes. If you have done any native iOS app development before, hitting Refresh to see the changes may seem like a miracle.

Now, let’s understand the code. At the top of the file is the following line:

'use strict';

This enables strict mode, which adds improved error handling to the React Native JavaScript code. The fifth edition of the ECMAScript specification introduced strict mode. Strict mode makes it easier to write secure JavaScript and convert bad syntax into real errors. This is very important for debugging any example and using undeclared variables.

Next is the following line:

var React = require('react-native');

This loads the React Native module and assigns it to a React Native variable that can be used in your code. React Native uses the same module-loading technology as Node.js with the require function; this is roughly equivalent to linking and importing libraries in Swift.

After that, you add the following snippet:

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

You are assigning multiple object properties to a single variable; this is called a destructuring the assignment. This cool feature was proposed in JavaScript ECMAScript 6. Although it is optional, it’s very beneficial; otherwise, every time you use a component in your code, you would have to use a fully qualified name for it, such as React.AppRegistry, React.Stylesheet, and so on. This saves quite some time.

Next, you create a view:

var HelloWorld = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
         HelloWorld !!
        </Text>
      </View>
    );
  }
});

React Native’s basic building blocks are called components. You can use the createClass method to create custom component classes. This class has just one function, render(). The render function is responsible for what is shown on the screen. You use JavaScript syntax extensions (JSX) for rendering the UI. JSX is a JavaScript syntax extension that looks similar to XML.

Now you define the styling of your app. Here you will use Flexbox; it is similar to what CSS is to HTML. For now, you can type this code. We will explain styling in the next chapter.

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  welcome: {
    fontSize: 25,
    textAlign: 'center'
  }
});

You can see that this styling is very similar to CSS; you can define font size, alignment, and so on.

The last step is to define the entry point and root component of the app:

AppRegistry.registerComponent('HouseShare', () => HelloWorld);

It’s Not a UIWebView

You are using web technologies, but your app does not have a web component; it has a native component. Open Debug image View Debugging image Capture View Hierarchy (see Figure 2-5).

9781484213964_Fig02-05.jpg

Figure 2-5. Using the native component

As you traverse through the tree of UIWindow, you’ll see that there is no UIWebView in the code, and “Hello World !!” is the call of RCTText, as shown in Figure 2-6.

9781484213964_Fig02-06.jpg

Figure 2-6. “Hello World !!” is the call of RCTText

Enabling Live Reload

Another cool feature of React Native is live reload. It reloads your application view inside the iOS simulator the moment there is a change. To activate this option, you need to access the developer menu from the application opened in the iOS simulator by pressing Ctrl + Command + Z and select the Enable Live Reload option. Now any change made in your JavaScript code will cause your app to reload automatically.

Why Is React Native Different?

Before you deep dive further into the React Native world, you must understand why there was a need for another framework to build mobile apps. We already live in a world full of frameworks and tool chains that are capable of building mobile apps. Prior to the inception of React Native, building mobile apps using web technologies was possible via two strategies:

  • WebView-based: These frameworks use common web technologies like HTML and JavaScript, and use WebView to load the application. An example is the popular framework Phonegap.
  • Native apps using web technologies: These frameworks again use common web technologies like HTML and JavaScript (to be precise, they imitate using JavaScript and HTML) to create native apps. An example is the popular framework Titanium Appcelerator.

Apps created using these strategies have performance issues. WebView-based apps are slow because they use the DOM, and DOM manipulations are expensive, which leads to performance issues. As stated in one of the blog posts at Flipboard (http://engineering.flipboard.com/2015/02/mobile-web/), “you cannot build a 60fps scrolling list view with DOM.” This is one of the fundamental problems with apps developed through this technique: although development time may be quick, you end up with a sluggish experience.

The other strategy, where the framework imitates JavaScript and HTML, and converts them to native code, has other challenges. Although the final app is native in nature, there is a basic issue during this conversion from JavaScript to native: it runs on the main thread. In these apps, you interface directly with native objects all the time, which leads to once again a slow and sluggish experience.

React Native is fundamentally different from these two approaches. It runs all layouts on separate threads, and your main thread is free to update the UI, which makes the animation and UI rendering smooth, just like 100% pure native apps.

React Native use the JavaScriptCore framework to run JavaScript. In iOS 7, Apple introduced a native Objective-C API for JavaScriptCore. This framework allows JavaScript and Objective-C to talk to each other. This means you can create and call JavaScript functions from Objective-C or call back into Objective-C from JavaScript. It all works like a charm.

React Native is different in one more aspect. As seen in your Hello World example, you write a component in JavaScript just like you would do with React, except that instead of using an HTML div, you use tags like View and Text. In the case of an iOS application, a View is basically a UIView.

The Anatomy of a React Native Application

Now let’s understand the application structure that the React Native init command has generated. If you open the project called HouseShare, it looks like a normal Xcode project. It has the following folder structure:

|ios
  |- HouseShare
  |- HouseShare.xcodeproj
  |- HouseShareTests
|android
node_modules
index.ios.js
index.android.js
package.json

 Note  The folder structure defined here might be changed or modified as the framework evolves, but the majority of the functionality remains the same.

If you open the project in Xcode, it will have a different folder structure. The “folders” in Xcode are actually groups and are not necessarily linked to a folder in Finder.

  • iOS: The iOS folder has two folders and one file. As seen above, there is a HouseShare folder, which has all the Objective-C code, such as AppDelegate, Images.xcassets, Info.plistLaunchScreen.xib, and other files. Another folder is HouseShareTests, which is where all your test cases reside. Finally, there is your Xcode project file, HouseShare.xcodeproj, which is used to load into Xcode to build your application.
  • package.json: This folder contains metadata about your app, and it will install all dependencies when you run the npm install. If you’re familiar with Ruby, it’s similar to a Gemfile.
  • node_modules: All of the Node modules mentioned in package.json will be downloaded to this folder. This folder also contains the code for the React Native framework.
  • index.ios.js: This is the file where you begin programming your iOS application.
  • AppDelegate.m: This is the starting point of any iOS app.
  • Android: React Native also supports development for Android. All your native Android code resides in this folder.
  • index.android.js: This file is where you begin programming for an Android application.

Let’s open the AppDelegate.m file from HouseShare/ios/HouseShare/AppDelegate.m:

#import "AppDelegate.h"

#import "RCTRootView.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  /**
   * Loading JavaScript code - uncomment the one you want.
   *
   * OPTION 1
   * Load from development server. Start the server from the repository root:
   *
   * $ npm start
   *
   * To run on a device, change `localhost` to the IP address of your computer
   * (you can get this by typing `ifconfig` into Terminal and selecting the
   * `inet` value under `en0:`) and make sure your computer and iOS device are
   * on the same Wi-Fi network.
   */

  jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];

  /**
   * OPTION 2
   * Load from pre-bundled file on disk. To re-generate the static bundle
   * from the root of your project directory, run
   *
   * $ react-native bundle --minify
   *
   * see http://facebook.github.io/react-native/docs/runningondevice.html
   */

//   jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"HouseShare"
                                                   launchOptions:launchOptions];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [[UIViewController alloc] init];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end

RCTRootView is an Objective-C class provided by React Native, which is inherited from the iOS UIView Class. It takes your JavaScript code and executes it.

It also loads the http://localhost:8081/index.ios.bundle URL, which has your code written in index.ios.js and also a program added by the React Native framework.

Debugging

Debugging with React Native is in line with how we debug web apps; in short, it’s really simple. To access debugging options, press Command + D within the loaded application from the iOS simulator. This will open a menu that provides several debugging options, as shown in Figure 2-7.

9781484213964_Fig02-07.jpg

Figure 2-7. Debugging options

You must disable this menu for the final build because your end user should not see these options. To disable it, open the project in Xcode and select: Product image Scheme image Edit Scheme (or press Command + <). Then select Run from the menu on the left and change the Build Configuration to Release.

Let’s review each of the options shown in Figure 2-7.

Reload

The reload option refreshes the screen in the simulator with the latest React Native code without compiling the project again. This can be done in two ways: one, by clicking the Reload option in the menu, as shown in Figure 2-7, or by pressing Command + R. This will reload all the changes made in the JavaScript code.

Any changes made in your Swift or Objective-C files will not be reflected this since these changes require recompilation. Also, if you add any assets like images, the app needs to be restarted.

Debugging in Chrome

This is one of the best and most used options for debugging your JavaScript code written in React Native. As with web apps, you can debug your React Native application in Chrome. When you click “Debug in Chrome” it opens http://localhost:8081/debugger-ui in Chrome (Figure 2-8).

9781484213964_Fig02-08.jpg

Figure 2-8. Debugging in Chrome

Install the React Developer Tools, which is a Chrome extension for debugging both your React application and React Native code. It allows you to inspect the React Native component hierarchies in the Chrome Developer Tools. To install it, please visit the Chrome webstore or go to the following URL: https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en.

Once the extension is installed, press Command + Option + J or select View image Developer image Developer Tools from your Chrome browser to access the developer tools console.

You will get a new tab called React in your Chrome DevTools. This shows that you the root React components that have been rendered on the page, as well as the subcomponents that they ended up rendering. You can also see props, state, components, and event listeners, as shown in Figure 2-9.

9781484213964_Fig02-09.jpg

Figure 2-9. Debugging in Chrome DevTools

Look at Figure 2-10 and you can see a similar hierarchy to your Xcode: Hello World is wrapped in RCTText and that is in turn wrapped in RCTview.

9781484213964_Fig02-10.jpg

Figure 2-10. Debugging the app with the React tab in Chrome DevTools

Debugging in Safari

If you do not have Chrome, you may also use Safari for debugging, but Chrome is preferred for debugging React Native apps.

Showing the FPS Monitor

Many applications use a lot of animations and graphics. FPS (frames per second) defines the smoothness of these animations for your application; this is used extensively in gaming apps. When you select “Show FPS Monitor” in the menu, it shows a few properties for your app in the simulator (Figure 2-11). Although you might not find much use for these properties in your Hello World app, they are great for animation-intensive apps to prevent them from getting into lethargic mode, creating a bumpy user experience. See Figure 2-11.

9781484213964_Fig02-11.jpg

Figure 2-11. Additional properties in the simulator

The Inspect Element

You can also inspect a React Native element from the simulator, somewhat similar to how you inspect an element in a browser, although you can’t currently change live values of properties as you can in a browser. For now, you can see your style sheet properties for any object. Click the HelloReact!! text (Figure 2-12) and it will open the details of that element.  

9781484213964_Fig02-12.jpg

Figure 2-12. Click the text to see element details

The details of that element are shown in Figure 2-13 at the bottom left.

9781484213964_Fig02-13.jpg

Figure 2-13. Font details

You can see that the font size for Hello World is 25 and it is aligned at the center.

Starting Profiling

Profiling is used to measure performance. The profiling session provides insight into which parts of your code are used most, how much time it takes, and which sections of your code you should improve. You can also find the time spent in each method from the number of times the profiler stopped on a method.

The following URL links to a very nice blog post that will give you a good overview of how to use profiling with Xcode: www.raywenderlich.com/23037/how-to-use-instruments-in-xcode.

Summary

In this chapter, you were introduced to React Native. You set up the React Native development environment and you wrote your first application. You also learned about the folder structure of React Native applications and how to debug. You are now all set to take a deep dive into creating a user interface with React Native for your iOS application.

In the next chapter, you will learn how to create stunning user interfaces by mastering Flexbox. You’ll see how to navigate from one component to another, how to add images to your unembellished application, and how to create a ListView and a ScrollView using React Native.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.231.155