
React is one of the most popular JavaScript framework as of 2019. It took web development by storm when first introduced and its popularity has been increasing among the developer community ever since.
React Native took this one step further when first introduced in 2015 and helped build Native iOS apps with common knowledge of web technologies like JavaScript. In just a few years, React Native has become an important player in native mobile development, and extending its support for both Apple iOS and Google Android was a game changer. This required us to write second edition of this book, which covers both platforms end to end to help you create stunning React Native apps.
This book is divided into ten chapters and each one teaches a unique aspect of building React Native applications. By end of this journey we believe you will be a master developer with React Native and will be able to publish your app to the Apple App Store or Google Play Store. We commence our journey with an introduction to React in Chapter 1 , where you learn about core React concepts like Virtual DOM, one-way data flows, props, and state, and also build a small React application. In Chapter 2 we cover how to set up React Native and start building a simple Hello World program. This chapter also cover the anatomy of a React Native project and how to debug the application. In Chapter 3 we discuss design patterns like MVC, as well as new programming paradigms such as Flux and Redux. In this chapter you learn about Redux core concepts, how to use Redux with React Native, and the benefits of including it in a React Native application. Chapter 4 covers how to build a user interface (UI) with the help of Flexbox, navigation with React Navigation, and few critical UI components, such as touchable highlight, listview, scrollview, and more. In Chapter 5 we address how to implement device capabilities, including creating apps to use features like GeoLocation, MapView, Native Alert, WebView, and deep linking.
Chapter 6 covers a key feature that is essential to any real-world application: communication with back-end servers. In this chapter you learn how to make requests to get data from a server and post data back to a server using various available React Native options. In Chapter 7 , we discuss how to access native application programming interfaces (APIs) that do not have a corresponding JavaScript library; this is building Native Bridge. This skill helps us harness all the features of native iOS and Android development. Chapter 8 covers how to write tests for our React Native application using Jest, and also introduces snapshot testing. This chapter also introduces a static type check commonly used in the React Native world, called Flow. In Chapter 9 , once you have learned how to create a full-featured React Native application, it is equally important to test it with users and push it onto the Apple App Store and Google Play Store. This chapter describes how to beta test a React Native application with the distribution systems available for iOS and Android. We also cover how to create builds for iOS and Android, which is essential for submitting an application to the Apple App Store and Google Play Store. In the final chapter, Chapter 10 , you learn about some popular React Native libraries and where to go next, how to get help, and how to stay in touch with the amazing React Native community.
In all, we hope that by end of this book you are confident in building your next mobile application with React Native and launching it for both iOS and Android. All the best!
We would like to thank our families, who saw us through this book, talked things over, offered constructive feedback and provided support through our strenuous schedule without which conceiving this book wouldn’t have been possible.
Also, we would like to thank Louise Corrigan, James Markham and the entire team at Apress. And especially Nancy Chen who gave us complete creative freedom to do things over the course of this book which some time took more time then expected. Writing a book is a long and arduous journey, but you all made it so easy for us.

is a software architect and author of the books React Native for iOS Development and RubyMotion iOS Development Essentials . He is also a seasoned technical reviewer for books on the topics of React, React Native, and Microservices with top publishers. He has extensive experience in DevOps, mobile, and Web development.
In other avatars, Akshat frequently speaks at conferences and meetups on various technologies. He was an invited speaker at the React Native Conference EU, Devops@scale Amsterdam, TheDevTheory Conference, RubyConfIndia, and the #inspect-RubyMotion Conference Brussels. He was also the keynote speaker at technology leadership events in Bangkok and Kuala Lumpur on TDD. Besides writing code, Akshat spends time with his family, is an avid reader, and is obsessive about healthy eating. More information about Akshat can be found at https://www.akshatpaul.com/ .


has a background in mechanical engineering from the University of Ibadan in Nigeria and has been a front-end developer for more than three years working on both Web and mobile technologies. He also has experience as a technical author, writer, and reviewer. He enjoys programming for the web, and occasionally, you can also find him playing soccer. He was born in Benin City and is currently based in Lagos, Nigeria.
The journey of a thousand miles begins with one step.
—Lao Tzu
Introduction to React
Virtual Document Object Model (DOM)
One-way data flow
React installation and setup
Creating a first React Hello World app
Introduction to components
Props and state
Let’s get started! React is different from most popular web technologies, and you will learn why as you move through this chapter. Its core concepts will open your mind to a new way of thinking if you have spent a considerable amount of time with traditional frameworks; this new way of thinking is sometimes called the React way of thinking. You might have heard the phrase “Write once, run everywhere,” but dismissed it as nearly impossible due to the explosion of different form factors (web, mobile, tablets). React has a different guiding principle: “Learn once, write anywhere.” That seems quite different, and liberating. We begin this first chapter with a quick tour of React, which will help prepare you for React Native. If you have an elementary knowledge of React, you can skip this chapter and move on to Chapter 2.
According to the official documentation, React is a JavaScript (JS) library (not framework) for creating user interfaces (UIs). It was built in a combined effort by teams from Facebook and Instagram. React was first introduced to the world in 2013, and has taken it by storm, with community-wide acceptance and the benefit of being the technology at the heart of Facebook. According to official documentation, some consider React to be the V in a model-view-controller (MVC) framework, because React makes no assumptions about the rest of the technology stack used. You can use whatever technology you wish and you can create a single section of your app with React or React Native; you can also conveniently make changes in an already created application by incrementally adding React to it.
Do we really need another JavaScript library in a world full of JavaScript libraries and frameworks? There is hardly a month that goes by without a new JavaScript framework introduced.
React came into existence because its creators were faced with a significant problem: how to build large applications in which data change frequently. This problem occurs in almost any real-world application and React was created from the ground up to solve it. As you know, many popular frameworks are MVC or model-view-wildcard (MV*), but here’s a point to be noted and reiterated: React is not an MV* framework. It’s a just a library for building composable UIs for UI components with data that change over time. Unlike popular JS frameworks, React does not use templates or Hypertext Markup Language (HTML) directives. React builds UIs by breaking the UI into many components. That’s it, nothing else. This means that React uses the full features of programming languages to build and render views.
React uses JavaScript extensively: Traditionally the views in HTML are separated from the functionality in JavaScript. With React, components are created and there is one monolithic section where JavaScript has intimate knowledge of your HTML.
Extendable and maintainable: Components are formed by a unified markup with its view logic, which actually makes the UI easy to extend and maintain.
Virtual DOM: React applications are blazing fast. The credit for this goes to the virtual DOM and its diffing algorithm.
One-way data flow: Two-way data binding is a great idea, but in real-world applications it produces more pain than benefit. One of the common drawbacks with two-way data binding is that you have no idea how your data get updated. With one-way data flow, things are simple: You know exactly where data are mutating, which makes it easier to maintain and test your app.
To have a strong foundation with a new technology, it’s necessary to understand its core concepts. The next section explores a few unique concepts of React, which will bring you one step closer to understanding this amazing technology.

Virtual DOM and diffing algorithm operations
Manual DOM manipulation is messy, and keeping track of the previous state of the DOM is very hard. As shown in Figure 1-1, React solves this problem by keeping two copies of a VDOM. Next, a diffing algorithm is applied on these two VDOMs, which essentially checks for the changes that occurred and returns a stream of DOM operations. These DOM operations are then applied to the actual browser DOM.

Components with virtual VDOM
This feature of VDOM is not just important, but a killer feature of React. DOM access is super slow, and honestly speaking, the world has made it worse by hitting the DOM again and again in most applications. To make your application fast, you should access the DOM as little as possible, and this is beautifully handled by the implementation of VDOM. You won’t notice this with a small and trivial application, but once your app grows to include thousands of DOM elements all trying to get updated, React will not let your performance suffer.
React is primarily the V in an MVC pattern, but before you dive into the idea of one-way data flow in React, you must understand the challenges of MVC frameworks. One of the biggest challenges of an MVC framework is managing the view. As you know, the view component of the MVC framework is mainly the DOM representation. It is simple when you write code that interacts with the DOM, but it is very complicated for the framework to handle various DOM manipulations.

Two-way data binding

Unwanted spaghetti relationship
Another issue with this system is that making changes comes at a very high cost. When you introduce a new developer to an application that is this complex, it’s tough to understand the impact one change might have in this abyss of spaghetti relationships.

React Native’s one-way data flow
To understand practical examples, you must first set up your environment to run your React code. Because React is just a node module, there are lot of different ways to set up a React project. We can include React in existing projects using npm or yarn and start using it. If you are starting a new project, we recommend using the create-react-app npm package. It is an out-of-the-box command-line interface (CLI) created by Facebook that creates a basic structure for the React app and takes care of ES7+ translation though Babel and Webpack. You don’t need to focus on configuration; instead you can focus on writing React code. You can find more details about this module on its official npm page. If it interests you, you can also check its github repo from here to look at its documentation: https://www.npmjs.com/package/create-react-app .
This command installs create-react-app globally.
If you want to use the multiple-node version on the same machine, we can use nvm: https://github.com/creationix/nvm
where application name is the desired name of the application. We need to use npm naming conventions, so the name should be in lowercase and cannot start with a dot or underscore.
Running that command installs the dependencies needed to build your project, and it generates the initial project structure. Create React App installs the latest version of React and React-DOM, as well as the latest version of react-scripts, a development dependency that manages all other development dependencies that include starting, testing, and building your app. Create React App uses Webpack and Babel under the hood, but it generates only the files you need to work on your React project.
It will automatically open http://localhost:3000/ in your default web browser and you can see the first page of our app.
yarn is a package manager like npm. It was created by Facebook and is the default that comes packaged with create-react-app. It is up to you to choose whether you want to use yarn or npm.
One of the advantages of yarn over npm is that npm always requires an Internet connection, whereas yarn can be used offline if you have installed it at some point in the past. Yarn is also very fast when it comes to package installations, which saves a lot of time in day-to-day development.
Components are the smallest units in React application development; they are indeed the most fundamental part of React. React is a library for building UIs and components are the key for creating any UI in React. You might think of it as widgets (like in Flutter) that you can plug in anywhere. These components define how DOM elements are created and how users can interact with them. The whole concept of components is that they are totally encapsulated, making them easy to test and reuse.
Creating reusable components is a work of art, and React provides many features for you. We will do a deep dive into them soon, but first let’s open the hello world app we created.
This is the main App component. As you can see, it’s just a JavaScript file that contains some HTML code. If you have been building software for some time, you know it is a best practice to keep your HTML and JavaScript code separate. Looking at this example, it goes against this fundamental best practice. The reason this best practice exists is to decrease coupling and increase cohesion, which means we write the UI in HTML and logic in JavaScript. The challenge with this approach is that we can only attach behavior to HTML through HTML elements (like ID, class, etc.). A library like jQuery is a good example of this. As your files grow, it becomes difficult to manage and test your code. React components solve this problem very well.
It lets you create JavaScript objects using HTML syntax. Components serve two purposes: templates and display logic. Therefore, markup and code are tied together intimately. Display logic often is quite complex and to express it using template languages does become difficult. The best way to solve this problem is to generate HTML and components from JavaScript itself. React JSX solves these problems with its HTML-type syntax by creating React tree nodes.
Going back to the preceding code snippet, App is a JavaScript class that is inherited from the React Component class API. Components can be created in two ways: one using class and the other using function. Components created using function are also called stateless components. We discuss this in detail in later chapters.
The App class has a render function or method. As the name suggests, it is used for rendering of our content, JSX markup. render is always a pure function, which means it is immutable. It’s like a single frame in a movie, as it represents the UI at a certain point in time. Updating the state inside a render will again call the render function, which once again, triggers render(), which then does the same thing, infinitely.
We are also importing Cascading Style Sheets (CSS) in the App component. Create React App uses Webpack, which takes care of importing CSS in the final bundle.

Browsing for the default message
This is the preferred way of creating a component if your state is not changing. It eliminates the class-related extra code like extends And constructors and makes the code more testable.
In this section, we explore the vital concepts of components, which will help you work with them easily. We will learn about Props and State, which help manage the flow of data or state. The Props and State objects have one important difference. Inside a class component, the State object can be changed, whereas the Props object cannot. Now let’s take a deeper look into both Props and State.
Props is simply shorthand for properties. Props are how components talk to each other and the data flow is immutable. Props are passed down the component tree from parent to children and vice versa. One key point to remember is that props cannot be mutated when referenced from a parent component.
If you refresh your browser, you will see a message from the property for your inner HTML.

Checking the console log
Prop validation is a great module that can help developers to hunt down bugs. Here, the propType keyword signifies a hash of prop names and their types.
The defaultProps will be used to ensure that this.props.text will have a value if it was not specified by the parent component.
In the last section, you learned about properties, which are static values that are passed into your component. State, on the other hand, is maintained and updated by the component. State is used so that a component can keep track of information in between any renders that it does. When you setState it updates the state object and then rerenders the component. We can think of props variables used for component initialization, whereas state is like internal data that affects the rendering of components and is considered private data.

Resulting message using state

Autopopulating the label
Like any other language, JavaScript class has constructors, a function that will get called whenever a new object is created. It’s important to call a super if we want to update the constructors. Calling this function will call the constructor of our parent class and allows it to initialize itself.
The constructor is only the place where you can change or set the state by directly overwriting the this.state fields. In all other instances you have to use this.setState.
This new function, handleChange, takes an event called (e) and updates the value text state.
The input box has an onChange event that calls your custom method handleChange whenever the state gets updated. As you type in the text box, your printed message gets updated instantaneously.
This chapter provided a quick tour of React. Before you begin with the next chapter, let’s recap what you have learned so far. We introduced the React library and the reasons behind its invention. Then you learned how to install and set up React. You studied the fundamentals of this technology, such as VDOM, one-way data flow, and JSX. You also got an introduction to components, and took a closer look at components, understanding how to use states and props with components.
Now that you are equipped to code and work in the React ecosystem, the your journey begins in the next chapter as we start working 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 development environment by installing the prerequisites and then you will create your first React Native application.
The best way to learn is through practical examples. We continue this theme throughout the book, as you will follow simple examples to learn React Native by programming yourself to understand the key concepts.
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
You might face a situation where different projects work on different Node versions. Therefore, it’s recommended you install Node Version Manager (NVM) to help keep multiple node versions that can be switched between projects.
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 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 UIs that 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/react-native .
Let’s do a quick, one-time setup of React Native. React Native is an assortment of JavaScript and Swift code, so you need tools that create, run, and debug your native application written in JavaScript. Let’s go one by one.
If you don’t want to use nvm, you can also install Node.js by running the following command in terminal:
>brew install node.
Homebrew is the package manager for Mac. You can also download the Node installer from https://nodejs.org and install it manually if you are using another operating system. For Windows operating systems you can visit https://nodejs.org and install Node using a wizard.
npm is also installed along with node, which is a package manager for Node.js. If you’re from the iOS world, it’s similar to CocoaPods.
For more information on React Native upgrades, you can refer to the Facebook official documentation at https://facebook.github.io/react-native/docs/upgrading .
You should only need to update the global installation of create-react-native-app very rarely, and ideally never.
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 following 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, and writing, and it’s how you will learn to program with React Native. As you proceed, this method will help you understand thoroughly 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 a few places, where we need to digress to explore a concept independently. Before you set it up, then, 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 a few 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 just create the basic structure for your project using React Native and some Hello World code.
Happy hacking!
So far we have used Expo a few times, so what is Expo? Expo is an open source tool chain that is built around React Native to help build iOS and Android apps. Expo is the fastest way to kickstart your React Native development. Because it comes out of the box with React Native, you don’t need to perform any additional setup on your machine. The only extra thing you need to do is to install the Expo application from the Apple App Store for iOS and the Google Play Store for Android. Using this app, you will be able to test and interact with the application you are building during the development stages.
You should see output similar to Figure 2-1.

Terminal output when we build a React Native application
To use this QR code, download the Expo app ( https://expo.io/ ) for iOS or Android on your device.
If you are using Android, just scan the QR code in your terminal from the Expo app and your app we automatically load. If you are using iOS, select “s” in your terminal, as shown in Figure 2-2.

Press the s key if you are using iOS

Expo link received in e-mail
Your mobile device needs to be connected to the same wireless network as your computer. Otherwise you will not able to open the app.

React Native application opened in Expo app
That was really quick and easy. Without installing the iOS and Android software development kit (SDK), we can run the app on our device using Expo.
Thanks to a single command, the basic structure of your project is in place and your application is loaded in the device. Also note that the terminal always needs to be open. 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 preceding request. The React Native Packager is responsible for reading and building the JSX (you’ll look at this later) and JavaScript code.
Set up your project in any editor you prefer. React Native does not force you to use nor does it have a preference for any specific editor, so you can continue to use your favorites.

Updated text component appears on the screen on save
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, pressing Refresh to see the changes might seem like a miracle.
This loads the React module and assigns it to a React variable that can be used in your code. React Native uses the same module-loading technology as Node.js; this is roughly equivalent to linking and importing libraries in Swift.
You are assigning multiple object properties to a single variable; this is called destructuring the assignment. This cool feature is in there in versions of JavaScript after ES6. 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.Stylesheet, and so on. This saves quite a bit of time.
React basic building blocks are called components. You can use the React.Component method to create custom component classes. This class has just one function, render(), which 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.
You can see that this styling is very similar to CSS; you can define font size, alignment, and so on.
Using the Expo iOS or Android application to test your app, there is a downside: You can’t always carry your devices for testing your application. For such purpose there are simulators provided by both iOS and Android to be set up on your development machine. The following are few prerequisites to set them up.
iOS apps can be developed only on an Apple Mac with OSX installed. You need OSX version 11 or above.
You need Xcode 9 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.
Test applications on actual devices.
Access beta OS releases.
Test flight for beta testing.
Submit your app to the App Store.
React Native requires a recent version of the Java SE Development Kit (JDK).
Android SDK
Android SDK Platform
Performance (Intel ® HAXM)
Android Virtual Device
Install Android Virtual Devices (AVDs) by opening the AVD Manager from within Android Studio. You can also use genymotion.

Running demo application on simulator
This will install Expo client on the emulator and run your React Native app. You can also use commands like yarn ios or yarn android to start the simulator with the app installed in it rather than loading the app inside the Expo simulator app.

Using the Native component

“Hello World !!” is the call of RCTText
Another cool feature of React Native is live reload. It reloads your application view inside the iOS simulator the moment there is a change. By default it is active. To deactivate this option, you need to access the developer menu from the application opened in the iOS simulator by shaking the device and then selecting the Disable Live Reload option.
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 a blog post at Flipboard (see 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 might 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 once again to 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 percent pure native apps.
React Native uses 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 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.

Ejecting Expo application
The folder structure defined here might be changed or modified as the framework evolves, but the majority of the functionality remains the same.
iOS: The iOS folder has two folders and one file. As seen earlier, 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.
App.js: This is the file where you begin programming your 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.
RCTRootView is a Swift 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 index bundle URL, which has your code written in App.js and also a program added by the React Native framework.
After ejection, you need to use Xcode to run the iOS app and Android Studio to run the Android app.

Starting the application without Expo

Building the application using Xcode
This will open the simulator and you can see the app running.

Debugging options for React Native applications
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 ➤ Scheme ➤ 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-12.
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: selecting the Reload option from the menu or 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 because these changes require recompilation. Also, if you add any assets like images, the app needs to be restarted.

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 https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en .
Once the extension is installed, press Command + Option + J or select View ➤ Developer ➤ Developer Tools in your Chrome browser to access the Developer Tools console.

Debugging in Chrome DevTools

Debugging the app with the React tab in Chrome DevTools
If you do not have Chrome, you can also use Safari for debugging, but Chrome is preferred for debugging React Native apps.

Additional properties in the simulator

Click the text to see element details

Font details
You can see that the font size for Hello World is 25 and it is center aligned.
In this chapter, you were introduced to React Native. You learned how to set up the React Native development environment and you wrote your first application. You also learned about Expo and the folder structure of React Native applications and how to debug. You are now all set to explore creating a UI with React Native for your iOS application.
Chapter 3 introduces about Flux and Redux, a pair of very important design patterns that are commonly used with React Native applications.
Simplicity is prerequisite for reliability.
—Djikstra
Flux is an application architecture introduced by Facebook for building client-side applications. It complements the React paradigm of composable view components by using a unidirectional data flow. It’s more of a pattern than a framework, and one can start using Flux immediately without an excess load of code. Redux is a predictable state container for JavaScript applications, which means it helps us to write applications that behave consistently in different environments: client, server, or native. It also makes your applications easy to debug and test.
Before we delve into its details, it is important to know one of the most popular, commonly used MVC patterns. We can then learn about what challenges we face with MVC and how Flux and Redux can solve these challenges.
MVC pattern
MVC problem
Flux
Flux deep dive
Redux
Redux core concepts
Redux with React Native
Benefits of using Redux
Model: This element manages the behavior and data of an application.
View: This is the representation layer of the model in the UI.
Controller: This element takes user input and makes necessary manipulations to the model, which causes the view layer to get updated.

Simple MVC pattern

MVC pattern for a large application
Wow! That is an explosion of arrows. Welcome to the real world where many models and views interact with each other. A controller triggers another model and this goes on like spaghetti, which often ends up in an infinite loop. The worst part is that it’s really difficult to debug code in such a situation, eventually making the system fragile. Well, Facebook faced a similar problem with this pattern and solved it with a new pattern called Flux.
Flux abjures MVC in favor of a unidirectional data flow. Flux works well because the single directional data flow makes it easy to understand and modify an application as it grows and becomes more complex. Earlier we found that two-way data bindings lead to cascading updates, where change in one data model leads to an update in another data model, making it very difficult to predict what would change as the result of a single user interaction.

React App data flow
Although controllers do exist in a Flux application, these are controller views, where views are found at the top of the hierarchy that retrieve data from the stores and forward these data to their children.

Flux data flow
As an application grows, eventually the dispatcher becomes more vital, as it is responsible for managing dependencies between stores by invoking the registered callbacks in a specific order.
When a user interacts with a React view, the view sends an action (usually represented as a JavaScript object with some fields) through the dispatcher, which notifies the various stores that hold the application’s data and business logic. When the stores change state, they notify the views that something has updated. This works especially well with React’s declarative model, which allows the stores to send updates without specifying how to transition views between states.
It improves data consistency.
It is easier to pinpoint the bugs.
You can perform more meaningful unit tests. Because all the states of a module are there in the same place, we can test a module independently.
It includes predictable code.
One of Facebook’s most popular features was its chat functionality. However, it was extremely buggy and had a high rate of negative user feedback. The new chat system that Facebook implemented is using a Flux pattern that provides a seamless experience. You can have look at example chat code in a Facebook React example at https://github.com/facebook/flux/tree/master/examples .
As we now know what Flux is, let’s look into and understand the concepts like dispatcher, store, and action
The dispatcher is the central hub that manages all data flow in a Flux application. It is essentially a registry of callbacks into the stores and has no real intelligence of its own; in essence, it is a simple mechanism for distributing the actions to the stores. Each store registers itself and provides a callback. When an action creator provides the dispatcher with a new action, all stores in the application receive the action via the callbacks in the registry. Dispatcher also acts like a traffic controller. If it gets an action even when the data layer is still processing, it makes sure to run the action. With the dispatcher, you know where your action starts and what changes it makes to the data layer. There are cascading effects that build up in between. You are indeed in full control of your system.
As an application grows, dependencies across different stores also increase. Imagine, for example, we have a situation where Store A needs Store B to update itself first, so that it can itself know how to update, too. We need the dispatcher to be able to invoke the callback for Store B and finish that callback before moving forward with Store A. To assert this dependence, a store needs to communicate with the dispatcher to first complete the action to update Store B. The dispatcher provides this functionality through the waitFor() method.
The dispatch() method provides a simple, synchronous iteration through the callbacks, invoking each in turn. When waitFor() is encountered within one of the callbacks, execution of that callback stops and waitFor() provides us with a new iteration cycle over the dependencies. After the entire set of dependencies has been fulfilled, the original callback then continues to execute.
Further, the waitFor() method can be used in different ways for different actions, within the same store’s callback. In one case, Store A might need to wait for Store B. In another case, though, it might need to wait for Store C. Using waitFor() within the code block that is specific to an action allows us to have fine-grained control of these dependencies.
Problems arise, however, if we have circular dependencies; that is, if Store A needs to wait for Store B, and Store B needs to wait for Store A. This could wind up in an endless loop. The dispatcher now available in the Flux repo protects against this by throwing an informative error to alert the developer that this problem has occurred. The developer can then create a third store and resolve the circular dependency.
Stores contain the application state and logic. Their role is somewhat similar to a model in a traditional MVC, but they manage the state of many objects—they do not represent a single record of data like ORM (Object Relational Mapping) models do. More than simply managing a collection of ORM-style objects, stores manage the application state for a particular domain within the application.
As mentioned earlier, a store registers itself with the dispatcher and provides it with a callback. This callback receives the action as a parameter. Within the store’s registered callback, a switch statement based on the action’s type is used to interpret the action and to provide the proper hooks into the store’s internal methods. This allows an action to result in an update to the state of the store via the dispatcher. After the stores are updated, they broadcast an event declaring that their state has changed, so the views can query the new state and update themselves.
When new data enter the system, whether through a person interacting with the application or through a web API call, those data are packaged into an action—an object literal containing the new fields of data and a specific action type. We often create a library of helper methods called action creators that not only create the action object, but also pass the action to the dispatcher.
Different actions are identified by a type attribute. When all of the stores receive the action, they typically use this attribute to determine if and how they should respond to it. In a Flux application, both stores and views control themselves; external objects do not act on them. Actions flow into the stores through the callbacks they define and register, not through setter methods.
Letting the stores update themselves eliminates many entanglements typically found in MVC applications, where ascading updates between models can lead to unstable state and make accurate testing very difficult. The objects within a Flux application are highly decoupled, and adhere very strongly to the Law of Demeter, the principle that each object within a system should know as little as possible about the other objects in the system. This results in software that is more maintainable, adaptable, testable, and easier for new engineering team members to understand.
Now that we have read about Flux, next we discuss another pattern called Redux. Redux can be considered a predecessor to the Flux architecture, and it is also inspired by the functional programming language Elm. Redux was created by Dan Abramov in mid-2015. During that time, the React world was going through major changes and new things were coming every other day. No one, though, could imagine that a small library of just 2 KB would create such a tectonic shift in the way we interact with and create React applications.
Redux was built on top of functional programming concepts. Functional programming by design allows us to write clean and modular code that is easier to test, debug, and maintain. With functional programming, code is in the form of small functions that are isolated in scope and logic, thus making the code reusable. Because small pieces of code are isolated in nature, there is hardly any coupling and these tiny functions can be used as modules in an app. In functional JavaScript you will see pure functions, anonymous functions, and higher order functions used very often. Redux uses pure functions a lot, so a good understanding of this concept is important.
Pure functions return a value based on arguments passed to them. They do not modify or mutate existing objects, but they return new ones. These functions do not depend on the state from which they are called, but they return only one and the same result for any provided argument. That’s why they are very predictable. Because pure functions do not modify any value, they don’t have any observable side effects. Redux uses something called reducers, which are pure functions. We will learn in detail about reducers and other Redux code concepts in the next section.

Redux data flow
Actions are events that send data from the application (user interactions, API calls, form submissions, etc.) to the store. The store always gets the information from actions. Internal actions are simple JavaScript objects that have a type property (usually constant), describing the type of action and payload of information being sent to the store. To send them to the store we use store.dispatch().
Action creators, as the name suggests, are the functions that create actions. It is easy to conflate the terms action and action creator, so do your best to use the proper term. To call these action creator functions anywhere in the app we use dispatch. As mentioned earlier, the dispatch() function can be accessed directly from the store as store.dispatch(), but more likely you’ll access it using a helper like react-redux’s connect() method. You can use bindActionCreators() to automatically bind many action creators to a dispatch() function.
Action creators can also be asynchronous and have side effects. This is an advanced topic, so we don’t need to go in-depth right now.
This is a very simple reducer that takes the current state and an action as arguments and then returns the next state. In the case of complex applications, we will be using the combineReducers() utility that is provided by Redux. It combines all the reducers of the app into a single index reducer. Every reducer is responsible for its own part of the app’s state, and the state parameter is different for every reducer. The combineReducers() utility makes the file structure much easier to maintain.
getState(): Allows access to state.
dispatch(action): Allows state to be updated.
subscribe(listener): Registers listeners.
replaceReducer(nextReducer): Replaces the reducer currently used by the store to calculate the state.

List of project folder structure
You would have to create all these folders: components, containers, reducers, store, and a TodoApp.js file. Within these folders we would have more JavaScript files reside inside our action, stores, reducers, and components. This way our code stays modularized and the logic remains isolated. Here, the Redux part is managed under the action, reducer, and the store folder, but we would need components that will use them.
Hence, we have two folders here: components, which consists of plain dumb components, which are the presentational components of the app having no idea that Redux exists or not in the app. Second, we have smart components that interact with Redux, and they reside in the containers folder.
Here, we have imported something called createStore from redux. Here we are combining all our reducers with rootReducer and exporting the same. Soon you will see how we have created two reducers that we plan to use with our store using rootReducer.
Here, we have imported our store and also used something called Provider from react-redux. Once we pass our Provider and store within that, it can be accessed anywhere in TodoApp no matter how many levels deep it is. Great! With this our store is set up.
Although our store is setup, we require some UI components. If you look at the containers folder, we have an addTodo component, which is a simple TextInput that will be used to create a new todo. Therefore, on this text input field there will be some action that will trigger it to create a new todo.
Here we have two actions—ADD_TODO and TOGGLE_TODO—that are responsible for adding a new record in the list and marking a record complete using their respective actions. We are able to determine the type of actions using action.type.
Here we are using something called CombineReducers from redux. This helps is keep the logical part separate but use it such in a way that we have only one reducer.
This will update the todo list and also the text input state with an empty string so that new values can be added later.
To display the data, we use a dumb component whose only purpose is to display the to-do list. This component has nothing to do with Redux. You can find this dumb component inside component/TodoList.js

Showing the to-do list on an iPhone
As you saw, there is some work involved in using Redux along with your application, and as with any new piece of technology or new pattern, developers should always ask this: Why should I use it in the first place?”
Expected outcomes: With Redux there is no confusion about where to locate our one source of truth; that will always be the store.
Maintainability and organization of code: With a strict structure in place and predictable outcomes, maintaining the code becomes easier. Redux is also particular about how the code should be organized, and this becomes pivotal in maintaining the source code as an application becomes large.
Tools: With developer tools, developers can track what’s happening in the application in real time.
Community: Redux is not something that has just appeared; it has indeed passed the test of time. The community is flourishing, and you can easily get support and regular updates for the library.
Ease of testing: Redux functions by design are small, pure, and isolated, which makes them perfect candidates to for which to write tests. Redux apps automatically make testing easy for the application.
In this chapter you learned about the Flux pattern, how it differs, and how it solves a fundamental problem differently from the traditional MVC pattern. We also looked closer at Flux core concepts. Next, you learned about the successor of Flux, Redux, its core concepts, benefits, and how to use it with React Native applications, which will be useful in real-world applications and in the upcoming chapters. Chapter 4 covers how to create UIs and navigation in React Native apps. Finally, you learn how to use animation in your views.
A user interface is the process of shifting from chaotic complexity to elegant simplicity.
—Akshat Paul
React Navigation
Flexbox
TouchableHighlight
ListView
ScrollView
Animations
Any experienced software professional will agree: The success of an app depends on the fact that it not only works flawlessly, but also looks great. Therefore, a great UI can make a huge difference in the success of your app.
The layout system is a fundamental concept that needs to be mastered to create great applications. Let’s begin by understanding how to navigate within iOS and Android applications using React Native.
React Navigation is one of the popular JavaScript libraries for handling routing in React Native applications. iOS and Android have different ways to handle navigation, and react-navigation takes care of this for both platforms.

HomeScreen React component loaded
createStackNavigator takes a route configuration object and because it returns a React component, we can use this in the App component. It provides a way for your app to transition between components and manage navigation history, gestures, and animations, which is natively provided in Android and iOS.
Right now, we have used just the HomeScreen component. Let’s add one more screen and use react-navigation to route to this new screen.

Navigating using React Navigation
We have used createStackNavigator , which has created screens as a stack that can be navigated with the back button at the top. It manages a stack of screens to provide a drill-down interface for hierarchical content.

Header styling updated
If you are only targeting iOS you can also use NavigatorIOS. It wraps UIKit navigation and allows you to add a backswipe feature to your app. NavigatorIOS manages a stack of view controllers to provide a drill-down interface for hierarchical content. Now that we know what NavigatorIOS does, let’s implement it in our project.
NavigatorIOS helps with the most basic iOS routing. A route is an object that describes each view in the navigator.
We have done a little bit of styling in this section, which might be something new for you if you come from a grid-layout background. React Native uses Flexbox for styling, which is discussed in detail next.
In creating the layout in the previous example, you must have seen the flex property mentioned in the styles. This appears because React Native apps use the Flexbox layout model.

Screen in portrait mode

Screen in landscape mode
Now, let’s review the flex properties Flex-direction and flex.

Changing the orientation of the box

Changing the property to column

Container in 2:1 ratio

Container with three views
This will divide the view into a 2:1:2 ratio, because their flex values are in the ratio 2:1:2.

View in 1:1:1 ratio
We can see that now the screen is divided in a ratio of 1:1:1, because the flex values of the views are in a ratio of 1:1:1. With Flexbox, it is easy to create layouts that can resize according to screen size and orientation. This is just an introduction to Flexbox; we explain more properties throughout the book as and when needed. You can also find more options at https://facebook.github.io/react-native/docs/flexbox.html .
React Native has a built-in component, Image, that will help us to display images, including network images, temporary local images, and also images from a local disk, such as the Camera Roll. To start, we display local images.

Adding images
We can also give any server image URL as the source, and the Image component will take care of loading it from the network. For a different screen size you can also give images of a different density by using the @2x and @3x suffixes in the same folder. We will load an image from a server later in this chapter.
Touch is one of the ways to interact with a view in an application. TouchableHighlight is a React Native component that helps us create clickable views that give a proper response in the event of a touch. To understand TouchableHighlight with an example, let’s continue building our app by adding one more view to list the housing options. This will be done by clicking on the show house image, which will redirect to another component.
Let us review what we have done here; we have added an onPress attribute to our TouchableHighlight component for the List Properties section. Whenever someone presses the List Properties image, it calls navigate('HomeListScreen') .

Clickable View with TouchableHighlight

Property name and address

Thumbnail image with property name and address
In the previous section, we populated one element. In this section, we populate a list of data using ListView. Before we embark on that, let’s learn a bit more about a different way to show the ListView component in React Native. React Native has two components: FlatList and SectionList.
FlatList is a component designed for populating vertically scrolling lists of dynamic data. The minimal steps are to create a FlatList data source and populate it with an array of data similar to the native TableView data source.
ListView looks very similar to TableView, but the implementation doesn’t actually use TableView. Rather, it uses ScrollView behind the scenes. Features like swipe to delete, reordering, and so on, cannot be used directly through ListView.
We will show the list of house address, as an example of the most common representation of data in mobile devices. With our HouseShare app, we will create a table view showing a list of properties, each of which has a thumbnail image to the left side. The rest of the details should appear next to it.

Scrollable addresses
We have once again specified what all components will be using in this section. There is a new component added, FlatList .
data is the source of information for the list.
renderItem takes one item from the source and returns a formatted component to render.
keyExtractor tells the list to use the IDs for the React keys instead of the default key property.
Although we are not using ScrollView in our HouseShare application, it can be used as an alternate way to populate a list just like we used ListView. ScrollView is one of the most versatile and useful controls, as it is a great way to list content that is greater in size than the screen size.
There are many other options available with ScrollView; for documentation and examples, you can visit https://facebook.github.io/react-native/docs/scrollview.html .
ScrollView is easy to use and it simply renders all its React child components at once, whereas FlatList renders items lazily, just when they are about to appear, and removes items that scroll far off screen to save memory and processing time.
Animations are crucial when it comes to creating a good user experience. If you think of any popular mobile app, you will likely find animation at the center of an immersive user experience. React Native provides an animation API to perform different types of animations with ease.
Animated.timing(): Animation based on time range.
Animated.decay(): Animation starts with an initial velocity and gradually slows to a stop.
Animated.spring(): This is a simple single-spring physics model that tracks velocity state to create fluid motions as the toValue updates, and can be chained together.
Animated.parallel(): This starts an array of animations all at the same time.
Animated.sequence(): We can perform an array of animations in order, waiting for each to complete before starting the next.
Run the app and you can see the FadeIn animation on the Home List page. There are several different configurations available, which are documented at https://facebook.github.io/react-native/docs/animated#configuring-animations .
React Navigation
NavigatorIOS for back-swipe functionality across apps
The Flexbox layout model
TouchableHighlight, a wrapper for making views respond properly to touches
Using ListView for efficient scrolling of vertical lists
Using ScrollView for listing content larger than the screen size
Using the Animate API of React Native to animate a View.
The next chapter covers different device capabilities like MapView, AsyncStorage, Native Alert, WebView, and deep linking.
Software will give you respect, but hardware will give you the power.
—Akshat Paul
MapView and GeoLocation
AsyncStorage
Native Alert
WebView
Deep linking
In this section, we will learn how to use iOS and Android location services with a React Native application. Location services are used very often in many popular apps, especially in travel, navigation, ride sharing, and so on. This single feature significantly improves the user experience and the bonus is that it’s very easy to implement.
react-native-maps ( https://github.com/react-community/react-native-maps ) is one of the best modules for map views. It includes numerous customization options available to help you design the best possible experience with maps.

GeoLocation MapView
Here, we have set the initial state for the region with certain latitude, longitude, latitudeDelta, and longitudeDelta parameters, which will be later set when we render the function with the MapView component. In the MapView component, we are using the region state, which is supplied with latitude, longitude, longitudeDelta, and latitudeDelta. These should always be numbers (integer or float), as they help us plot a specific region on the map. Finally, we have added some style with Flex and registered our component.

GeoLocation with Google Maps
There are numerous customization options available. You can check https://github.com/react-community/react-native-maps/blob/master/docs/mapview.md for more details.

MapView with added parameters
In this final part of our geolocation application, we will display our present latitude and longitude on the screen. In the previous example, we had a constant location; in this part, we will move to our current location in real time. That sounds like something exciting, so let’s start building it. There are two ways to check for the current location on our maps. One is to simply add showsUserLocation={true} to the MapView component. Another way is to use NSLocationWhenInUseUsageDescription geolocation. Let’s try the first option. If you are using gelocation on an existing project, you need to update NSLocationWhenInUseUsageDescription in info.plist for iOS and <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> in AndroidManifest.xml for Android. Because we have created a project with Expo, which initially uses react-native init, gelocation is enabled by default.

Access location prompt

Moving to a specified map location in the code

Map showing the current location

Current location displayed in the console log

Change location using Simulator

Location changed to freeway

Storage is updated

Text from the AsyncStorage mechanism
This time the text below, “This text is from local storage,” is coming from the AsyncStorage mechanism that we have put in place.
We use this AsyncStorage React component within our App component. Previously, we also specified a key that we will use with AsyncStorage.
Finally, we set up a UI style with some self-explanatory Flex settings and register our AsyncStorageExample component.
Alerts are used to provide important information to application users. Basic alerts consist of a dialog box with a specific title, message, and buttons. Occasionally alert boxes appear in an application to display a piece of important information. The buttons for an alert could either be a simple OK to proceed with the app, or OK, Cancel, Ask Me Later, and so on, which require the user to make a decision. Tapping this button could be linked to execute an inPress callback to execute a piece of code. By default an alert dialog box will have one button.

A button that will open an alert dialog box when clicked

An alert dialog box

Two buttons added on the screen

Select Button 1, Button 2, or Cancel
Tapping Button 2 fires an onPress callback that uses the alert method of Alert to set title, message, and buttons for our alert box. In this part of the NativeAlert component we have three buttons.

WebView with a URL
Deep linking is a technique that allows an app to be opened to a specific UI or resource, in response to some external event. The deep refers to the depth of the page in an app’s hierarchical structure of pages. This is a very important feature for user engagement, as it also makes an app more responsive and capable of navigation to arbitrary content in response to external events like push notifications, e-mails, web links, and so on.
There are two ways of implementing deep linking: using a URL scheme or universal links. Although URL schemes are a well-known way of using deep linking, universal links are the new method Apple has implemented to easily connect your web page and your app under the same link. We implement URL schemes in our example that will handle external URIs. Let’s suppose that we want a URI like myapp://article/4 to open our app and link straight into an article screen that shows article number 1.
We have thus far created React Navigation and created routes for two pages. We have configured our navigation container to extract the path from the app’s incoming URI. On Android, the URI prefix typically contains a host in addition to the scheme, so we have used myapp://myapp/.

Deep linking using Xcode

Running the app with iOS

Traversing to the DeepLink page

Traversing to the DeepLink page
This chapter covered various capabilities of iOS and Android devices using React Native. These capabilities helped us build features beyond just a UI. We learned how to use GeoLocation and loading maps for your app, AsyncStorage to persist data, Native alerts to share important info in your app, WebView to load HTML5 content, and finally deep linking.
Chapter 6 discusses how to interact with a back-end server because no real-world application is complete without connecting to a back end and consuming APIs.
Communication is everyone’s panacea for everything.
—Tom Peters
XMLHttpRequest
WebSocket
Fetch
Getting data from a server
Posting data to a server
Earlier you were getting all the data from a dummy data object, which was static within your application. It’s rare that any production application will work entirely with static data. Fortunately, React Native provides many ways to interact with network APIs. The following sections cover the ways the network stack is supported in React Native.
Using XMLHttpRequest is quite tedious. However, because it is compatible with the browser API, it lets you use third-party libraries directly from npm (e.g., Parse). For more information on this API, please refer to its documentation at https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest .
Now that you know how to interact with network APIs, let’s use one of the options, fetch, to get and post data to a server. To keep things simple, we have hosted a simple back-end server with restful APIs that you can consume for your application.
We will be using following the URLs to get and post data to a back-end server. For a quick test, you can use curl to see the response you get from making a request to these URLs.
You might see few results here that are created by other readers of this book.

Populating the app with static data fetched from a server
Earlier we had created a stateless component, but because we would like to use life cycle methods and maintain state, we have modified our stateless component to a state component.
Here, we have created a constructor that sets the initial state for the dataSource property as null. This is the property that will store the data we will pull from a back-end server.
Next, we use a life cycle method componentDidMount() . We are making use of this life cycle method because we assume we would only be required to make a get call to the back-end API to get the list of properties once.
The structure of this request is straightforward: We use fetch to make a call that returns a promise. This promise is then resolved and we pass the response JSON to dataSource using the setState object .

Showing the Add New Property button on the home page
This is a simple form having two input fields, name and address, along with styling, which we added at the end. Just as in constructor, the state for these two properties was set to an empty string. We update the state with setState once the user fills in the form and pass it to the function onPressButtonPost.
You should notice we added a bind in render here. Because we are using ES6 while declaring React components, React no longer autobinds. Therefore we must resolve this by explicitly calling bind in render.
There are other binding patterns to handle this. Here are a few popular ones in React:
1. Binding in render (the one we have used in our application)
onChange={this.handleChange.bind(this)}
2. Using an arrow function in render
onPress={e => this.handleChange(e)}
3. Binding in constructor itself
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
4. Using an arrow function in call property
handleChange = () => {
// call this function from render
// and this.whatever in here works fine.
};
Here, we are using the updated values of the name and address properties and making a post request using fetch. Once our request is completed we get an alert box with a Created message.

Form to submit a record

Page to add new house

Alert after successful submission
This API shows data submitted by various readers of this book. Your data set might differ.

Output showing Mr. Paul’s Mansion address
By default, iOS will block any request that’s not encrypted using Secure Sockets Layer (SSL). If you need to fetch from a clear text URL (one that begins with http) you will first need to add an App Transport Security (ATS) exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely. Note, however, that since January 2017, Apple’s App Store review requires reasonable justification for disabling ATS.
This chapter covered various network APIs that are reimplemented from the ground up by the React Native team. You also learned about various options like XMLHttpRequest, WebSocket, and Fetch. Because no application is complete without making server calls, you added this capability into your housing application and learned how to get data from a server, add new records, and save them to a server.
In Chapter 7 we explore Native Bridge for iOS and Android. By using Native Bridge we can access Native iOS or Android APIs from JavaScript.
Learn the rules like a pro, so you can break them like an artist.
—Pablo Picasso
What is Native Bridge
Preprequisite for Native Bridge
Native Bridge for iOS
Native Bridge for Android
The concept of Native modules is a bit advanced, but in our experience every production-quality application at some point requires you to delve into a little bit of native programming. Therefore, we consider this an essential skill to know in your journey to becoming a master in React Native.
To better undersand Native modules, we will create a Counter example in Swift for iOS and Java in Android, and this will be used in our React app. This will be a cross-platform example, so the same React code will work in both iOS and Android.
Because many readers of this book might not have worked in Swift or Java, we have tried to keep the use of both these languages very basic, so it should be easily understandable.
Xcode for running the app for iOS
Android Studio for running the app for Android
React Native
This will create the basic structure of the React Native app. It also contains two folders, iOS and android, which have native code in Objective-C and Java, respectively. We first learn about bridging in iOS, and then use same repo to build for Android.
We will create a Counter class in Swift, which will have a static class variable count and two methods: one for incrementing the count and the other for getting the count value. We will then access this Swift class from JavaScript. Let’s start by opening the CounterNativeModuleApp.xcodeproj file in the ios folder. It should open Xcode with your iOS code.

Creating a new file in Swift

Selecting proper group in Xcode

Creating a bridging header
We can see that two files, Counter.swift and CounterNativeModuleApp-Bridging-Header.h, are created by Xcode.
In the preceding code we have created class Counter, which is inherited from NSObject. The root class of most Objective-C class hierarchies is NSObject, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
You can see that we have used @objc before a function and class. This will make that class, function, or object available to Objective-C
The @objc attribute makes your Swift API available in Objective-C and the Objective-C runtime.

Creating an Objective-C file
string (NSString)
number (NSInteger, float, double, CGFloat, NSNumber)
boolean (BOOL, NSNumber)
array (NSArray) of any types from this list
object (NSDictionary) with string keys and values of any type from this list
function (RCTResponseSenderBlock)
We need to import NativeModule from react-native. The Counter method increment can be accessed using NativeModules.Counter.increment() . We have created a Button and clicking on that button calls the increment method.
Now let’s run the app from Xcode by pressing Command + R. Make sure React Native code is running. If it is not, then run npm start.

App running in a simulator

Increment displayed in console log
We can see that we have called a Swift class method from a JavaScript React component.
Remember, if you change any code in iOS Swift or Objective-C or Android Java, you need to rebuild the project. Only then will changes be reflected.
Module Counter requires main queue setup since it overrides ‘init’ but doesn’t implement ‘requiresMainQueueSetup’ . In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.
Main thread: Where UIKit works.
Shadow queue: Where the layout happens.
JavaScript thread: Where your JavaScript code is actually running.
Every native module has its own GCD (Grand Central Dispatch) Queue unless it specifies otherwise.

Application running without warning
Now let’s add the count value to our React screen. To do so we will add the getCount function to counter.swift and call that method from JavaScript code. We will create this method as a callback.
React Native Bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events.
The getCount() method receives a callback parameter that we will pass from your JavaScript code. We have called callback with an array of values, which will be exposed in JavaScript. We have passed NSNull() as the first element, which we consider an error in callback.

Application demo in simulator
Try to refresh the page by pressing Command + R. The count value will be the same and does not reset to 0. If you rebuild the code, however, then the value will be reset to 0.
In this section we will make the same JavaScript code work with Android. This time we will create a Counter class in java and expose the same functions, increment and getCount, to Javascript.

Open the React Native app in Android Studio

Creating a Counter class
We have created the Native module Counter , which is a Java class that is inherited from ReactContextBaseJavaModule. ReactContextBaseJavaModule requires that the function getName is called; this is always implemented. The purpose of this method is to return the string name of the Native module, which represents this class in JavaScript. Here we will call this Counter so that we can access it through React.NativeModules.Counter in JavaScript. Instead of Counter, you could also use a different name.

Creating a new Java class
We need to override the createNativeModules function and add the Counter object to the modules array. If this is not added there, it will not be available in JavaScript.
We don’t need to change any JavaScript code written in iOS, as we have exposed the same class name and function. If you skipped the iOS section earlier, you need to copy the React JavaScript code from App.js.

Run the application from Android Studio

Application running in Android emulator
We can see the counter change when we click Increment and the JavaScript code is calling the Java code.
This chapter covered Native Bridge for both iOS and Android. You created a class in Swift and Java and through NativeBridge you were able to access these classes in JavaScript code.
In Chapter 8 you learn about testing in React Native, including type checking using Flow, using Jest with React Native, and understanding how to use snapshot testing.
Testing is not the point. The point is about responsibility.
—Kent Beck
Static type checking with Flow
Jest with React Native
Snapshot testing
Flow is a static type checker for JavaScript. It’s not essential to use Flow, but it really enhances your development efficiency. Type checking allows you to detect possible issues early by running tests on your project code base. In short, we would say Flow is a productivity module for developers.
This will create a .flowconfig file where all your Flow configurations will reside.
Typically, at the beginning of any project, you will find no errors. As you proceed with day-to-day development, however, you can find issues right away and resolve them.
You can code faster without the hassle of running the source code every time to find any issues or bugs.
It is especially helpful for extensive projects with multiple team members working in parallel. Refactoring can become a nightmare, and Flow helps you focus only on your changes and eliminates worry about breaking other parts of the source code.
Flow helps developers to understand idiomatic JavaScript. It understands and provides feedback on common JavaScript patterns, which helps developers to create elegent solutions.
Flow provides real-time feedback, hence saving a great deal of time and improving code quality.
Flow provides easy integration. As seen earlier, it takes only a few minutes to set up Flow with your project.
Jest is a unit test framework that is built on top of Jasmine. React Native supports testing of components using Jest (it’s also the recommended framework used at Facebook for React Native). Besides React Native, you can also use Jest for other JavaScript projects built using TypeScript, Node, Angular, React for Web, Vue, and many more.
Snapshot testing: Jest allows you to create tests that keep track of large objects. This helps you to write better test cases of UI elements.
Zero configuration: Jest works out of the box and is configuration free.
Fast and isolated: Tests are parallelized by running them in their own processes, which helps maximize performance. Jest runs previous failed tests first and reorganizes the runs based on how long it took to execute the tests.
Simple APIs: Jest makes use of simple conventions that developers are used to. Jest covers the entire toolkit, with updated documentation that is well maintained.
Code coverage: No additional setup is required to pull a built-in code coverage report.
This was the case if you generated your project using the React Native CLI, but what about Expo? In previous chapters we used Expo to speed up our development process. With Expo the setup process is slightly different because the Expo CLI does not come with Jest out of the box.
For this you would have to set up Jest manually with an include jest-expo, which is not very complicated. You could try this in an existing Expo application you created in a previous chapter or set up a new one.
Snapshotting is a really useful technique in UI development that helps ensure that there are no unexpected changes in the UI during development. With Jest we can capture snapshots of React trees, which help us to compare if there was a breaking change in subsequent changes.
A snapshot test case for a mobile app will render a UI component, take a snapshot, and then compare it to a reference point in the past by storing a snapshot alongside the test case. If the test fails, that means two snapshots did not match due to an unexpected change in the UI. Snapshots should be updated to a new version when a satisfactory UI component is ready.
Perfect! Our test failed, and this shows how snapshot testing with Jest really helps during development of a substantial React Native application if one developer makes a change, for example, that might hinder the UI build by someone else.
Testing is a crucial component in any mobile app development. In this chapter you learned about using Flow to keep your code type checked to assist in detecting issues with your code early and resolving them before they become bugs. Next, you learned about testing with Jest and how to set it up for both React Native CLI apps and those generated using the ExpoCLI. In the end, we introduced the powerful technique of snapshot testing with Jest, which makes building UIs and maintaining them much easier.
Chapter 9 covers iOS and Android app submission to the Apple App Store and Google Play Store, respectively.
The last 10 percent to launch something takes as much energy as the first 90 percent.
—Rob Kalin
The Apple and Google Play distribution systems
Creating a build for iOS or Android
Beta testing
Only Apple ID | Apple Developer Program | Enterprise Program | |
|---|---|---|---|
Xcode developer tools | ✓ | ✓ | ✓ |
Xcode beta releases | ✓ | ✓ | ✓ |
Test on device | ✓ | ✓ | ✓ |
Developer forums | ✓ | ✓ | ✓ |
OS beta releases | × | ✓ | ✓ |
Advanced app capabilities | × | ✓ | ✓ |
Code-level support | × | ✓ | ✓ |
Distribution outside Apple App Store | × | ✓ | ✓ |
App Store distribution | × | ✓ | × |
App Store connect | × | ✓ | × |
Safari extensions | × | ✓ | × |
Offering custom apps | × | ✓ | × |
Distribution of custom apps to your employees | × | ✓ | × |
Distribution of your proprietary apps to your employees | × | × | ✓ |
Cost | Free | US$99 (annually) | US$299 (annually) |
To create your Apple Developer Account, visit https://developer.apple.com/ .
In the case of Android, you explicitly do not need to have a paid account from Google Play at the time of development or testing. However, eventually when you have to distribute your application (i.e., publish it to the Google Play Store) you would have to pay a one-time registration fee of US$25. However, this will only be required toward the end of the chapter if you wish to publish your app to the Play Store.To learn more about the Google Play Console visit https://play.google.com/apps/publish/ .

Apple Developer console
The first option is Certificates, Identifiers & Profiles and the second one is App Store Connect. The App Store is the place where we will upload our application build to be submitted to Apple for publishing our app to the App Store and also for beta testing our application using TestFlight.

Beginning the development and distribution process

Selecting development and distribution certificates
We will require both because we plan to publish our application to the App Store and the process is the same for both. Select iOS App Development and continue to the next step. There you will see instructions how to generate the certificate on your Mac machine, which will be then uploaded. For this you will make use of the Keychain utility.
In the User Email Address field, enter your e-mail address.
In the Common Name field, create a name for your private key (e.g., John Doe Dev Key).
The CA Email Address field should be left empty.
In the Request is group, select Saved to disk.

Certificate upload page on Apple Developer portal
Once the CSR file is uploaded, click Continue. At the last step you will have the option to download the certificate. Double-click it and it will get loaded in your Keychain.
Next, follow the same steps and set up distribution certification. On successful completion you can check both your installed certificates in Keychain ➤ My Certifications.

List of App ID page on Developer portal

Registering an App ID in the Apple Developer portal

App ID shown in the Apple Developer portal

iOS Provisioning Profiles list page in the Apple Developer portal

Add iOS Provisioning Profiles page on the Apple Developer portal
Click Continue. Your Development Provisioning profile will be generated. Double-click it and it will be loaded in your Xcode automatically. Before proceeding to the next section, create a Distribution Provisioning profile for our sampleReactNative app using the same process.
Now that all our basic setup is completed, in the next section you learn how we create a build for our application and distribute it among our team members using TestFlight.

Folder structure of iOS project

Xcode General tab settings for the project
Use the App ID you had created in previous section as the Bundle Identifier. This has to be same, as mentioned in the Developer console, and unique for every application you create. It is essentially a unique identifier for your app in Apple’s system.
Next, let’s add some app icons and a launch screen for our sample application. It’s fine to keep your launch screen simple, with just text that comes out of the box when you initialize a React Native application. However, we must add all types of icons for our build to be successful and submitted to Apple for both App Store release and testing with TestFlight.

Icon image set screen in Xcode

An app for creating an icon set on Mac

Icon image set screen in Xcode
Once this is done, you will see all your icons automatically set up and you’re ready for the next step, which is setting up your launch screen.
Select LaunchScreen.xib to add or modify the launch screen for your application. In our sample application, we will keep the same default launch screen because it won’t break our build or stop us from uploading it. However, for a real-world application that is supposed to be published to the App Store, it is better to have a proper launch screen.

Xcode archive generation

Xcode Organizer

Xcode Organizer detail screen

App Store Connect home page

App Store Connect create new app

App Store Connect form to create a new app
Fill it out with the proper details for your application. You can select the appropriate Bundle ID from the drop-down list. A SKU has to be added, which can be different from the Bundle ID. This SKU is not visible to App Store users. For user access, if you have created any specific user group already you can select it. If not, select Full Access, especially if this is your first application.

Organizer success screen
You can check your application build on App Store Connect in a few. From App Store Connect, you can submit your application to Apple for review. After a successful review of your application without issues and errors, your app will be live on the Apple App Store for users in two to five days.
Before you publish your application for end users, it must be thoroughly tested. This process is called beta testing and can be achieved using TestFlight.
Just like Apple, Google expects all Android apps to be signed with a certificate before they get installed on a device either for testing or publishing in the Google Play Store.
When you execute this command, it will ask few questions and require a password to be set for your keys. Please remember the password because it will be used later when applying these settings for your React Native application.

Android folder structure of app
Always make sure to keep your keys private and never commit in the project directory.
As mentioned earlier, provide the password you set when you were generating your keys.
This will generate the apk build that can you can find at android/app/build/outputs/apk/release/app-release.apk. This apk can be distributed to users and submitted to the Google Play Store.
TestFlight is a utility that is included when you set up your Apple Developer Account. It allows you to invite users to test your application, provide you with feedback, and provide you with valuable test information like crashes, and so on.
Each build is active for 90 days and you can invite up to 25 internal testers (which does not require App Store review) and up to 10,000 external testers, which is only applicable after App Store review.

App Store Connect TestFlight tab
You will see the recently uploaded build available. It will mention missing compliance. Under App Information, select Test Information from the menu pane. Click the Missing Compliance message again and click Start Internal Testing.
You can invite up to 25 users to participate in internal testing. To add users, return to the App Store Connect home screen and select Users and Access. From there, you can add your testing users and segregate them into groups if required.
Your testers would have to install the TestFlight application from the Apple App Store to access the build, which will be installed separately on your iOS device.
TestFlight is a good option, but it is limited to only iOS device testing. Besides TestFlight we would recommend TestFairy and HockeyApp as alternatives that can be used for both iOS and Android. Whereas TestFairy is a paid utility, HockeyApp is completely free (at the time of this writing).
In this chapter we finally reached the end of the development cycle for a mobile application, creating a build that can be tested by users and submitted to the Apple App Store or the Google Play Store. You learned about the signing process for both systems: Whereas Apple has specific steps in its signing process, the Google Android process is fairly quick. Both, though, are designed to keep the rights and devices of users from being misused. You also learned about beta testing with TestFlight and some other popular options.
Civilization advances by extending the number of operations which we can perform without thinking about them.
—Alfred North Whitehead
Popular React Native libraries
Community, Help, and where to go from here
From the time of its inception the React Native ecosystem has grown by leaps and bounds. The React Native community is vibrant and exceptionally productive: With every passing week, something new is always coming up to untangle the complications of development. By the time you have reached this chapter and we have completed this book, a lot more must have happened (later in this chapter we share ways to stay updated with the community). However, this chapter provides a curated list of libraries organized based on categories to help you increase the velocity of your React Native development.
Styled-components allows you to write actual CSS code to style your components. It removes the mapping between components and styles: Using components as a low-level styling construct makes it easy. See https://github.com/styled-components/styled-components .
Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as JSON with bodymovin (an After Effects extension to export anmations for the Web) and renders them natively on mobile platforms. Access the Lottie mobile library here: https://github.com/react-native-community/lottie-react-native .
This library is perfect for buttons, logos, and navigation and tab bars. It is easy to extend, style, and integrate into your project. It provides customizable icons for React Native with support for NavBar/TabBar/Toolbar, image source, and full styling. See https://github.com/oblador/react-native-vector-icons .
Formik is a simple library that helps you with the three parts that make forms in React complicated: getting values in and out of form state, validation and error messages, and handling form submission. See https://github.com/jaredpalmer/formik .
Redux-form is the most convenient way to manage a form state in Redux. To make use of this module you must have some idea about the Redux state container and higher order components. See https://github.com/erikras/redux-form/ .
ESLint is an open source project that has as its ultimate goal to provide a pluggable linting utility for JavaScript. There are many popular ESLint configurations available from popular projects that can import for your application while also creating new custom linting rules based on your requirement. See https://eslint.org/ .
Prop-types is a library that helps in runtime type checking for React props and similar objects. See https://www.npmjs.com/package/prop-types .
Flow is a static type checker for JavaScript that helps identify problems with your code early instead of guessing and checking. Flow provides real-time feedback as you code and make your changes. See https://flow.org/ .
Jest is a testing framework that is simple to use and integrate with your React Native application. It comes out of the box with React Native versions 0.38 and above. Jest also allows for snapshot testing, which is a brilliant way to manage changes in the UI. See url: https://jestjs.io/ .
Enzyme is a testing tool that was created and open sourced by Airbnb. It supports tons of features like shallow rendering, full DOM rendering, and static rendered markup. It is a great add-on, along with Jest. Enzyme APIs are intuitive and flexible as they imitate Jquery APIs for DOM manipulations. See https://github.com/airbnb/enzyme .
Chai is an assertion testing library based on test-driven and behavior-driven development. Just like Enzyme, Chai also enahances other testing frameworks. See https://www.chaijs.com/ .
Mocha is a JavaScript testing framework that helps make asynchronous testing simple. Mocha runs test serially and provides accurate reporting, while mapping uncaught exceptions to the correct test cases. See https://mochajs.org/ .
Axios is an HTTP client for JavaScript that helps make HTTP requests to REST endpoints and perform CRUD operations. Axois supports Promise API, intercept request and response, helps transform request and response data, and has many more features. See https://github.com/axios/axios .
If you plan to use GraphQL you will end up using Apollo, which is an implementation of GraphQL that helps manage data in the cloud. Apollo includes two open source libraries for the client and server, in addition to developer tools that provide everything you need to run a graph API in production with confidence. See https://www.apollographql.com/docs/react/recipes/react-native.html .
React-native-firebase is a collection of official React Native modules connecting you to Firebase services; each module is a lightweight JavaScript layer connecting you to the native Firebase SDKs for both iOS and Android. See https://github.com/invertase/react-native-firebase .
React Router is a collection of navigational components that compose declaratively with your application. Whether you want to have URLs that can be bookmarked for your web app or a composable way to navigate in React Native, React Router works perfectly. See https://reacttraining.com/react-router .
React Navigation was born from the React Native community’s need for an extensible yet easy-to-use navigation solution written entirely in JavaScript (so you can read and understand all of the source), on top of powerful native primitives. See https://reactnavigation.org/ .
Lodash is a JavaScript library that provides utility functions for common programming tasks using the functional programming paradigm. Lodash is the most commonly used library in any application and it is very popular in the JavaScript world. See https://lodash.com/docs/4.17.11 .
Ramda is a library designed specifically for a functional programming style, one that makes it easy to create functional pipelines and never mutates user data. See https://ramdajs.com/ .
Moment.js is brilliant for managing dates in JavaScript, which is something you will always stumble on when developing an application. See https://momentjs.com/ .
Reselect is a simple “selector” library with Redux. Having key features like selectors can compute derived data, allowing Redux to store the minimal possible state. Selectors are efficient; a selector is not recomputed unless one of its arguments changes. They are also composable, and they can be used as input to other selectors. See https://github.com/reduxjs/reselect .
Validation is part of any application. Validate.js serves this purpose by providing a declarative way of validating JavaScript objects. With Validate.js, validation constraints can be declared in JSON and shared between clients and the server. See https://validatejs.org/ .
This is a simple library, and as its name suggests, it provides device information for React Native for iOS and Android. It has a long list of APIs to provide in-depth information about the device on which an application is running. See https://github.com/rebeccahughes/react-native-device-info .
This section provides some suggestions on where to get help in the React Native community.
The React Native repository is maintained by a full-time Facebook React Native core team, but there is huge community that is always contributing to keeping this framework stable. You can always raise an issue if you find one with the framework in the GitHub repository, and there you can also find solutions to past issues. See https://github.com/facebook/react-native/issues . To report a bug in the framework you can use the bug report format available at https://github.com/facebook/react-native/issues/new?template=bug_report.md .
Stack Overflow is a place where people across the React Native community help each other. You can post questions and get answers pretty quickly. You can also help fellow developers as you proceed in your journey toward becoming an expert in React Native (or any other technology). By giving answers to various questions, your score on Stack Overflow increases, which is a kind of motivation for helping others. Many developers actually boast about their Stack Overflow stats. See https://stackoverflow.com/questions/tagged/react-native?sort=frequent for a list of exisiting questions on React Native. To ask a question with a React Native tag, go to https://stackoverflow.com/questions/ask?tags=react-native .
You should also stay in tune with the latest happenings in React Native with the official documentation available at https://github.com/facebook/react-native-website . The official blog of React Native maintained at https://facebook.github.io/react-native/blog/ will keep you updated on what is new. You can also connect with the official React Native Twitter account, which keeps updated with both React Native and Reactjs. See https://twitter.com/reactjs .
Sometimes if you don’t get an answer quickly on GitHub issues or Stack Overflow, it’s a good idea to get in touch with the larger community instantly. For that you can join the React Discord channel and connect with fellow developers. Incidentally, it’s not necessary for you have questions; you can always share your discovery or maybe your next open source React Native project. This is a good way to get some visibility. See https://discordapp.com/invite/0ZcbPKXt5bZjGY5n .
React Native Spectrum: https://spectrum.chat/react-native
React Native Facebook group: https://www.facebook.com/groups/react.native.community
Expo forum: https://forums.expo.io/
DevTo community: https://dev.to/t/reactnative
React Native on Medium: https://medium.com/tag/react-native
React Native, although very powerful, is still a young framework and its core team is always looking for great proposals, improvements, and discussions. Be part of this problem-solving effort and contribute to this thriving community. You can do this by following the formal channel at https://github.com/react-native-community/discussions-and-proposals .
Now we have reached the end of our book and our last summary. In this chapter we provided information about various React Native libraries that can expedite our development time and give access to the enormous treasure trove of features built over time by the React Native community. You also learned about how to stay updated on this fast-moving framework by getting information from the right sources.
Although you have learned a lot during the course of this book, to truly master this topic you have to keep practicing and creating apps. There is no better way to become an expert at a technology than learning on your own in a real-world scenario. You can contribute to the developer community by creating a module that still does not exist or by contributing to existing open source React Native repos. We are very excited about React Native, just like you, and look forward to seeing your work making a mark in the mobile development and React Native world.