INTRODUCTION =============== In this tutorial we will introduce you to building native apps using the React JavaScript library. # Good to know React Native is different from other JavaScript frameworks: 1) In React Native, you use JS, but the app's UI is fully native (unlike PhoneGap) It doesn't have the drawbacks typically associated with a hybrid HTML5 app. 2) Your UI is a function of the current app state, you are not burdened with constantly updating it 3) React Native's isn't "write once and run it on any platform", but once you learn should not be hard to port it into creating an Android app quickly. Swift is Apple's latest language for building iOS Apps. 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. We will be using XCode in this tutorial, but you can find community tools like Expo (https://expo.io/learn) to build React Native apps without having to touch XCode or Android Studio. #2 What are we building We are going to build an iOS app for searching movie listings and showtimes. The app will show how easy it is to consume APIs and do fun things. The tutorial will try to guide you through every step, step by step. This is a simple tutorial, I hope you will get a good feel for what it is like to create native apps that consume real APIs. API_KEYS =============== To save time, we will be using my developer API Keys in this tutorial. You can easily apply for your own after this session. It's possible we may run into Throttling or Thresholds using the keys, but let's see how it goes The Movie Database: api_key: '33546cde72549b76aec722c9b3e80943' [you don't need it right now, but to apply for your own developer key, go here: https://developers.themoviedb.org/3/getting-started/introduction] GraceNote: api_key: 'hkmmsu8mgj8te8hutxbff6nc' [to get your own developer key, go here: http://developer.tmsapi.com/member/register] You don't have to do anything with these note, just note that we will use them later. CREDIT/ACKNOWLEDGMENTS ========================= Inspirations for this tutorial are: 1) the Movie Database API documentation and code examples 2) the Gracenote Developer APIs documentation 3) Christine Abernathy and her Facebook team's apartment listings tutorial GETTING STARTED ================== We are going to go live through installing and getting our environment ready. As anything live and with scripts and frameworks, potetial for things to go wrong is high. Since we have limited time, we will be taking "the happy path", and that means I will be running it live and hopefully everybody can follow along on their Macs. But if people run into configuration or environment issues, we may not be able to debug case-by-case, as it would derail the entire thing. OK, let's get going: 0) Install XCode on your Mac, we will use it to log console messages and launch the Simulator React Native uses Node.js, a JavaScript runtime, to build your JavaScript code. If you don't already have Node.js installed, let's get it. 1) We will use a package manager called Homebrew to install node. Use the instructions on the Homebrew website: https://brew.sh/ 2) Then, install Node.js by executing the following in a Terminal window: brew install node 3) Next, use homebrew to install watchman, a file watcher from Facebook: brew install watchman This is used by React Native to figure out when your code changes and rebuild accordingly. It's like having Xcode do a build each time you save your file. 4) Next use npm to install the React Native Command Line Interface (CLI) tool: npm install -g react-native-cli This uses the Node Package Manager to fetch the CLI tool and install it globally Navigate to the folder where you would like to develop your app. For example, I created a folder called React in my home folder. In there, run the following in Terminal: react-native init MoviesAppv1 This uses the CLI tool to create a starter project, in its own folder, 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. OK, now in Terminal, run: cd MoviesAppv1 In the created folders and files you will find a few things: 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 MoviesAppv1.xcodeproj in the ios folder with Xcode. Select product->destination on the XCode menu, and pick iPhone 8 plus as the target device for example. Then build and run (Product->Build, and Product->Run on the XCode menu) The simulator will start and display the initial skeleton app If you see build-time warnings related to updating your 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. This is Metro Bundler, the React Native JavaScript bundler running under Node.js. Leave it running, you need it. 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: We will be mostly writing JavaScript code for this React Native tutorial. Instead of using Xcode, I use Sublime Text, other editors are fine as well. REACT NATIVE BASICS ======================= In this section, you'll be introduced to React Native basics as you begin working on MoviesAppv1. Open App.js in your text editor of choice and take a look at the structure of the code in the file: import React, { Component } from 'react'; // 1 import { Platform, StyleSheet, Text, View } from 'react-native'; const instructions = Platform.select({ ... }); // 2 export default class App extends Component<{}> { ... } // 3 const styles = StyleSheet.create({ ... }); // 4 Let's go through the code step-by-step: 1) Imports the required modules. 2) Sets up a platform-specific display message. 3) Defines the component that represents the UI. 4) reates 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. 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. Open index.js and take a look at the entry point file: import { AppRegistry } from 'react-native'; import App from './App'; AppRegistry.registerComponent('MoviesAppv1', () => App); This registers the imported component that serves as the app's entry point. It's time to start building your app. In App.js, add the following at the top of the file, just before the import statements: 'use strict'; This enables Strict Mode, which adds improved error handling and disables some less-than-ideal JavaScript language features. In simple terms, it makes JavaScript better! Inside the App class replace render() with the following: render() { return React.createElement(Text, {style: styles.description}, "Search for movies!"); } 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. Next, replace the const styles statement with the following: const styles = StyleSheet.create({ description: { fontSize: 18, textAlign: 'center', color: '#656565', marginTop: 65, }, }); This defines a single style that you've applied to the description text. 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 movie search app starting to take shape That's a JavaScript application running in the simulator, rendering a native UI, without a browser in sight. 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! 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 movies!” 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: return Search for movies (Again); This is JSX, or JavaScript syntax extension, which mixes HTML-like syntax directly in your JavaScript code. The tag represents a React component for displaying text. Text supports nesting, styling, and touch handling. More details here: https://facebook.github.io/react-native/docs/text.html When an element type starts with a lowercase letter, it refers to a built-in component like
. A React component or a user-defined component will start with a capital letter. You can also read more about JSX here: https://www.reactenlightenment.com/react-jsx/5.1.html 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: In App.js, modify the render method's body to the following: return Search for movies; Save your changes. Note that the simulator automatically refreshes to reflect your changes: ADDING NAVIGATION =================== We are going to use the standard stack-based navigation experience provided by UIKit's navigation controller. In App.js, find the import statements near the top and add a comma following the View destructuring assignment. Then add the following below it: NavigatorIOS, This brings in NavigatorIOS that you'll use for navigation. Next, replace the App class definition (just the "export default..." line) with the following: class WelcomePage extends Component<{}> { And add the following class below the WelcomePage component: export default class App extends Component<{}> { render() { return ( ); } } This constructs a navigation controller, applies a style and sets the initial route to the SearchPage component. 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 WELCOME PAGE ======================================== Add a new file named WelcomePage.js and place it in the same folder as App.js. Add the following code to this file: 'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, TextInput, View, Button, ActivityIndicator, Image, } from 'react-native'; This imports the modules you'll need to build the UI. Add the following Component subclass after the import statements: export default class WelcomePage extends Component<{}> { render() { return ( Search for movies playing near your zip. ); } } You can visualize the UI constructed by this component: a container with two text labels. Now, add the following style code at the bottom of the file: const styles = StyleSheet.create({ description: { marginBottom: 20, fontSize: 18, textAlign: 'center', color: '#656565' }, container: { padding: 30, marginTop: 65, alignItems: 'center' }, }); 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 WelcomePage from './WelcomePage'; 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. STYLES AND FLEXBOX ====================== So far, you've seen basic CSS properties that deal with margins, paddings and color. Flexbox is 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. It's 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 WelcomePage.js and insert the following just after the closing tag of the second Text element: