React Native - Building Mobile Apps with JavaScriptBuild real-world iOS and Android native apps with JavaScript Vladimir Novick BIRMINGHAM - MUMBAI... Understanding Why React Native is t
Trang 2React Native - Building Mobile Apps with JavaScript
Build real-world iOS and Android native apps with JavaScript
Vladimir Novick
BIRMINGHAM - MUMBAI
Trang 3React Native - Building Mobile
Apps with JavaScript
Copyright © 2017 Packt Publishing
All rights reserved No part of this book may be reproduced, stored in a
retrieval system, or transmitted in any form or by any means, without theprior written permission of the publisher, except in the case of brief
quotations embedded in critical articles or reviews
Every effort has been made in the preparation of this book to ensure the
accuracy of the information presented However, the information contained inthis book is sold without warranty, either express or implied Neither theauthor, nor Packt Publishing, and its dealers and distributors will be heldliable for any damages caused or alleged to be caused directly or indirectly bythis book
Packt Publishing has endeavored to provide trademark information about all
of the companies and products mentioned in this book by the appropriate use
of capitals However, Packt Publishing cannot guarantee the accuracy of thisinformation
First published: August 2017
Production reference: 1230817
Trang 4Published by Packt Publishing Ltd Livery Place
Trang 8About the Author
Vladimir Novick is developer, software architect, public speaker, and
consultant Coming from a web programming background, he started
programming for mobile using React Native around 2015 Vladimir works inthe web, mobile, VR, AR, and Internet of Things fields daily, developingcomplex enterprise-level software, consulting clients, contributing to opensource, and teaching, and talking at various meetups and conferences He isalso the author of several courses and workshops
Previously, Vladimir worked in the video, gaming, sports, and entertainmentindustries where he architected and developed large-scale web applicationsfor hundreds of millions of users, each month
I would like to thank several people who helped make this book a reality First, I want to thank Tatyana Novick, my wife Her encouragement and
support is something that kept me going forward Thanks to my kids for
supporting me and understanding that sometimes, daddy is busy writing Thanks to my dad for introducing me to programming back in the 90s.
Thanks to my mom, even though I kept the writing process a secret from you until the release, the idea of presenting you a hardcopied book was one of the initial drivers that encouraged me to write.
Thanks to Onkar Wani, my content development editor, whose
professionalism and help was invaluable.
Trang 9About the Reviewer
Vijay Thirugnanam is a React developer from Bangalore, India Before
working as an independent developer, he worked for more than 16 years,delivering software solutions as an engineer, a consultant, and a manager Hispast experience includes working in organizations such as ABB, Dell, andMicrosoft He holds a bachelor's degree from Indian Institute of Technology,Madras
His current passion is developing apps with React and React native Apartfrom that, he likes to take short breaks at resorts around Bangalore with hisfamily, his wife Shalini and daughter Tanishka
Trang 10For support files and downloads related to your book, please visit www.PacktPub com Did you know that Packt offers eBook versions of every book published,with PDF and ePub files available? You can upgrade to the eBook version at
www.PacktPub.com and as a print book customer, you are entitled to a discount
on the eBook copy Get in touch with us at service@packtpub.com for more
details
At www.PacktPub.com, you can also read a collection of free technical articles,sign up for a range of free newsletters and receive exclusive discounts andoffers on Packt books and eBooks
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt Mapt gives you full
access to all Packt books and video courses, as well as industry-leading tools
to help you plan your personal development and advance your career
Trang 12Customer Feedback
Thanks for purchasing this Packt book At Packt, quality is at the heart of oureditorial process To help us improve, please leave us an honest review onthis book's Amazon page at https://www.amazon.com/dp/1787282538 If you'd like tojoin our team of regular reviewers, you can e-mail us at
customerreviews@packtpub.com We award our regular reviewers with free eBooksand videos in exchange for their valuable feedback Help us be relentless inimproving our products!
Trang 14For my wife and kids, who believed in me and supported all the
way
Trang 15Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Piracy Questions
1 Understanding Why React Native is the Future of Mobile Apps
What is React Native?
The history of React Native
It all begun with ReactJS Hackathon, that grew bigger React Native today
The motivation of creating React Native Mobile development is too specific Taking the React approach
Making developer experience state of the art How React Native is different from hybrid applications? What are hybrid applications?
Why Native applications lead the way?
Is React Native really a Native framework?
How the React Native bridge from JavaScript to Native world works? Information flow
Architecture Threading model The benefits of React Native
Developer experience Chrome DevTools debugging Live reload
Hot reload
Trang 16Component hierarchy inspections Web-inspired layout techniques
Code reusability across applications Summary
2 Working with React Native
Setting up an environment for developing iOS and Android apps Installing projects with native code
Installing iOS dependencies Installing Android dependencies Installing JDK
Installing Android studio Installing SDK and built tools Setting up the ANDROID_HOME environment variable Creating an Android virtual device
The development environment Creating your application
Application with create-react-app and Expo Introduction to JSX and how it's used in React Native
What is JSX?
Children in JSX JSX props Stateful versus presentational components
Presentational components Stateful components React lifecycle methods
Mounting Updating Structuring React Native apps and their resemblance to HTML Thinking in React
Reusable components Containers
Basic React Native components The folder structure
Trang 17Images and media
Basic user interaction
Button
TouchableOpacity
TouchableHighlight
TouchableWithoutFeedback Getting feedback from your application ActivityIndicator
Embedding web content
Handling user input
TextInput
Restricted choice inputs
Platform-dependent components Detecting specific platform Extensions
Navigation in React Native
The Navigator component Summary
Trang 184 Debugging and Testing React Native
Debugging your React Native apps
Developer in-app menu Reloading your app Reloading Live reload Hot reloading Remote debugging
Debug with Chrome DevTools Debuging our device
Logging
In-app errors and warnings Errors
Warnings Inspecting React Native components
Performance monitoring Testing
Introduction to the Jest testing framework
Setup Preset system Basic syntax Snapshot testing your React Native components
Working with functions
Mocking modules
Summary
5 Bringing the Power of Flexbox to the Native World
Flexbox styling concepts and techniques
The flexbox layout Aligning elements Item dimensions How different is React Native styling from CSS or inline? Laying out our app
Dealing with background images Applying styles conditionally Best practices and techniques for styling your React Native applications Dimensions
Style sheet Split your styles
Trang 19Code your styles Extract common components Summary
6 Animating React Native Components
Understanding animations
Conventions How animation works
Using the LayoutAnimation API for simple animations Basic syntax
The preset system under the hood Using Animated API for complex animations
Animated values Calculations Animated functions
Interpolation Extrapolation Combining several animations to create complex sequences Panning and scrolling animations
Summary
7 Authenticating Your App and Fetching Data
Getting familiar with Firebase
What is Firebase?
Firebase setup Creating real-time database Managing permissions
Bringing Firebase to React Native and fetching data Initializing your app
Setting up Firebase database listeners Writing data to Firebase
Fetching data in React Native
Websockets support in React Native Fetching and uploading files
Setting up authentication at Firebase
Creating functional Login and Sign Up screens
Login screen The Sign Up screen Authentication logic Authenticating via social providers
Trang 208 Implementing a Flux Architecture with Redux or MobX
What is Flux architecture?
MVC problem The unidirectional data flow solution How it works
Redux concepts and usage
What is Redux?
Redux in a nutshell Three principles
A single source of truth State is read-only Changes are made with pure functions Basic building blocks
Actions Reducers Store Middleware Data flow
Connecting Redux to your app
Containers versus Components Provider
Using connect Getting relevant state keys with selectors Using redux-thunk for async actions
Async data flow Adding redux-thunk Centralizing side effects Mobx- a functional reactive Flux implementation What is Mobx?
Basic concepts State Derivations Actions Connecting MobX to our app
Summary
9 Understanding Supported APIs and How to Use Them
Linking libraries and APIs with native code
Trang 21Auto linking
Manual linking
Linking libraries
Configuring build phases
Getting familiar with a list of native APIs covered by React Native Notification APIs
Trang 22Retrieving and saving photos with CameraRoll API Getting your exact location with GeoLocation API IOS
Android Usage Learning about persistence with AsyncStorage API Responding to user gestures with PanResponder
The Gesture responder system PanResponder
Combining it with Animated Summary
10 Working with External Modules in React Native
Diving deeper into react-navigation
Navigators explained Navigation
Redux integration MobX integration Setting the app navigation structure for a real app The best open source packages to use
Visuals and animations react-native-vector-icons react-native-animatable lottie-react-native Shoutem UI NativeBase react-native-elements Social providers
Facebook OAuth
Additional APIs ExpoKit Maps Image Picker Video Toasts Camera Data related packages react-native-fetch-blob
Trang 23react-native-firebase react-native-push-notifications react-native-i18n
Boilerplates Writing your own Native modules
Diving into iOS and Objective-C Android
Creating folder structure and files Creating a native module Java class Creating a native module package Registering the package
Integrating React Native with the existing apps
Summary
11 Understanding Application Development Workflow by Recreating Twitter
Defining your application requirements
Defining your application architecture using a desired design
Setting up functional navigation and a wireframe for your application
SplashScreen The Login screen Main flow Home Discover Notifications Profile Tweet Mock data and style application screens including animations
Bringing Redux or MobX to your application and moving data mocks to a centralized stat e
Redux Refactoring all actions MobX
Using the Twitter API to work with real data
Summary
12 Deploying Your App to App Store or Google Play
Deploying iOS apps and how it's done in React Native
Join the Apple Developer program Creating a certificate for your device
Trang 24Signing your app to run on a device
Enable App Transport Security
Configure Release scheme
Registering our App ID
Archiving your app
Deploying Android apps and how it's done in React Native
Generating a Signed APK file
Distributing your APK
Introducing fastlane - automate your deployment workflow
Get to know Microsoft CodePush and integrate it with your application
So, how do we get started
Setting up your mobile client
Summary
Trang 25The world of web development is diverse and complicated New technologiesare introduced each year, creating competition between various libraries andframeworks for their place under the sun Some of these technologies haveemerged as web development community answers to problems introduced byconstantly evolving user needs Some were introduced by big corporations,such as Facebook or Google
For React Native, it all started as an internal hackathon project between thewalls of Facebook offices, and since then, it has grown to become one of themost popular frameworks React Native did something that web developershad tried to do for several years preceding the hackathon writing mobileapps in JavaScript There were several ways to write mobile apps, but all ofthem tackled the idea of hybrid apps
The main idea was to write apps in HTML, JavaScript, and CSS, and putthem inside a thin native container, which would be responsible for renderingall elements This was all about one code base written using web technologiesand rendered on both iOS and Android Many companies used this idea inproduction apps, but soon, everyone who wrote mobile hybrid apps figuredout that the performance difference was noticeable and multiple bugs led tofrustration among web developers trying to break into the mobile
development world
React Native had a different idea in mind Its idea was to use techniques used
in the React library, which came a few years before React Native, and createmodular components using JavaScript, but without HTML or CSS involved.React Native uses an internal mechanism to transform JavaScript to nativemodules With it, we are dealing with real native apps and not hybrid ones.Performance-wise, apps became identical to native ones, even for complexanimations and interactions React Native also wraps lots of iOS and
Android-core APIs and provides a simple bridging API to wrap your ownmodules or even integrate React Native app inside your existing app
Trang 26This book will start by explaining the difference between hybrid apps andReact Native and why it's one of the most popular frameworks, and looks likeit's going to be the future of mobile apps It will explain how React Nativeworks under the hood how JavaScript is compiled to native modules, andhow this bridge is architected After understanding the basic ideas and thearchitecture of React Native, the book will follow with software installationand setting up a React Native project It will cover different aspects of thesetup for iOS and Android, as well as community solutions and tooling tomake the app development experience better.
Then, the book will overview the basic React concepts used in React Native
It will ensure that readers feel comfortable with JSX syntax and understandwhat it represents Following these introductory sections, the book will divedeeper into explaining every single React Native component, API, and
technique in real-world examples such as WhatsApp, Instagram, and
YouTube It will teach you how to set up your animations, authenticate yourapp with Firebase or an external server, manage your application state withthe best state management libraries such as Redux and MobX, build complexnavigation systems in your app, test and debug your applications using built-
in as well as community-written tools The book will not only focus on ReactNative, but will introduce readers to the whole ecosystem of useful npm
packages that can be used in React Native It will cover how to properly linksuch packages with native application code and even write your own nativecode in Java or Objective C to be available inside JavaScript At the end ofthe book, all this knowledge will be summarized by creating a major part ofTwitter application pulling actual Twitter data In the final chapter of thebook, readers will also learn how to release their app to App Store or PlayStore, and learn about the tools available to speed up the release process
This book targets JavaScript developers who want to learn how to createnative mobile apps using React Native The reader must have basic
JavaScript knowledge, preferably of the latest version of JavaScript ES2015
If the reader lacks such knowledge, it's advised to walk through a fast tutorialavailable at https://babeljs.io/learn-es2015/
Trang 27What this book covers
Chapter 1, Understanding Why React Native is the Future of Mobile Apps,
introduces React Native as to the JavaScript framework for building nativemobile apps It describes the advantages of writing apps in React Native aswell as how React Native works under the hood
Chapter 2, Working with React Native, teaches the reader the basic building
blocks of React Native It covers how to set up your environment and createbasic layouts for iOS and Android Readers will get familiar with JSX syntaxand Stateful and Presentational components, and will get a taste of creating abasic one-screen app and running it in an emulator
Chapter 3, Getting Familiar with React Native Components, goes through all
the components React Native supplies to us This chapter will cover the
components that can be reused across both Android and iOS as well as
platform-specific components
Chapter 4, Debugging and Testing React Native, explores debugging and testing
React Native components It will cover basic debugging techniques to debugyour application while it's running, and it will explain how to write basic unittests for your app
Chapter 5, Bringing the Power of Flexbox to the Native World, informs the
reader of the concept of flexbox styling and how it's applied to styling ReactNative apps It covers the differences between styling with flexbox inside abrowser and in a React Native environment
Chapter 6, Animating React Native Components, focuses on animating UI
components with APIs supplied by React Native It will start with simplelayout animations and will dive into more complex animation examples used
in real apps
Chapter 7, Authenticating Your App and Fetching Data, outlines how to fetch
Trang 28data from a remote server and post data to it Readers won't have to set uptheir own server, but will get familiar with Firebase as a solution to "server as
a service" architecture Readers will learn how to retrieve and post data toFirebase as well as how to authenticate against Firebase They will also learnhow to authenticate an app with popular social networks
Chapter 8, Implementing a Flux Architecture with Redux or MobX, dives into
the flux architecture pattern and will dive deeper into Redux, the functionalstate management library, and flux architecture implementation, which is anindustry standard nowadays The chapter will cover the building blocks ofRedux and will guide the readers through the process of connecting Redux totheir React Native application and managing their application state with it Itwill also explore an alternative library for state management MobX as afunctional reactive way to deal with state management
Chapter 9, Understanding Supported APIs and How to Use Them, teaches that
it's important to understand which core APIs are supported in React Native.This chapter will cover most native APIs, such as various notification,
informational, and image-related APIs Readers will learn how to retrievephotos from camera roll, get geolocation, and respond to gestures At the end
of the chapter, readers will build a Tinder App card, swiping behavior withcomplex animations and the PanResponder API
Chapter 10, Working with External Modules in React Native, focuses on lots of
community packages that are considered standard and make React Native appdevelopment much faster It will dive deeper into navigation with the react-navigation package and will explain how it can be integrated both with
Redux and MobX; then, it will list famous open source packages that willspeed up your development, enhance mobile API coverage, and enrich yourapplication with prebuilt animations and interactions Then, it will cover howyou start writing your own native modules and connect them to the ReactNative world Finally, it will discuss integration between existing native appsand React Native
Chapter 11, Understanding the Application Development Workflow by
Recreating Twitter, presents a real-world application, Twitter, and will
Trang 29discuss how to create this application from scratch It will follow all thetechniques the book has taught to summarize the process of creating a fullyfunctional production app.
Chapter 12, Deploying Your App to App Store or Google Play, shows that
deploying your application to either App Store or Play Market can be a
challenge for web developers who are not familiar with this process Thechapter will cover deploying iOS and Android apps and using instant
deployment services to make your deployment even better than that of nativeapps
Trang 30What you need for this book
Since React Native is used for creating both iOS and Android apps, and iOSapps have to be developed on OSX, you will have to have a Mac, ideallyMacBook Pro with atleast 8 GB+ RAM If you want to develop only forAndroid, you can still use Windows PC and React Native to create androidapps; however, it's not covered in the book and may result in unexpectedbehavior While you will be able to follow most of the book, it will requireadditional troubleshooting if there are any errors
You will need an iOS and an Android phone, preferably the latest version
Trang 31Who this book is for
This book is for JavaScript developers who want to learn how to create nativemobile apps using React Native
Trang 32In this book, you will find a number of text styles that distinguish betweendifferent kinds of information Here are some examples of these styles and anexplanation of their meaning
Code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles areshown as follows: "If we take a look at our index.ios.js file, we will see thatour render method returns content wrapped in the View component"
A block of code is set as follows:
Trang 33New terms and important words are shown in bold Words that you see on
the screen, for example, in menus or dialog boxes, appear in the text like this:
"Clicking the Next button moves you to the next screen."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Trang 34Reader feedback
Feedback from our readers is always welcome Let us know what you thinkabout this book-what you liked or disliked Reader feedback is important for
us as it helps us develop titles that you will really get the most out of
To send us general feedback, simply e-mail feedback@packtpub.com, and mentionthe book's title in the subject of your message
If there is a topic that you have expertise in and you are interested in eitherwriting or contributing to a book, see our author guide at www.packtpub.com/author
s
Trang 35Customer support
Now that you are the proud owner of a Packt book, we have a number ofthings to help you to get the most from your purchase
Trang 36Downloading the example code
You can download the example code files for this book from your account at
http://www.packtpub.com If you purchased this book elsewhere, you can visit http:// www.packtpub.com/support and register to have the files e-mailed directly to you.You can download the code files by following these steps:
1 Log in or register to our website using your e-mail address and
password
2 Hover the mouse pointer on the SUPPORT tab at the top
3 Click on Code Downloads & Errata
4 Enter the name of the book in the Search box
5 Select the book for which you're looking to download the code files
6 Choose from the drop-down menu where you purchased this book from
7 Click on Code Download
You can also download the code files by clicking on the Code Files button onthe book's webpage at the Packt Publishing website This page can be
accessed by entering the book's name in the Search box Please note that youneed to be logged in to your Packt account
Once the file is downloaded, please make sure that you unzip or extract thefolder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktP ublishing/React-Native-Building-Mobile-Apps-with-JavaScript We also have other codebundles from our rich catalog of books and videos available at https://github.com/ PacktPublishing/ Check them out!
Trang 37Downloading the color images of
this book
We also provide you with a PDF file that has color images of the
screenshots/diagrams used in this book The color images will help you betterunderstand the changes in the output You can download this file from https://w ww.packtpub.com/sites/default/files/downloads/ReactNativeBuildingMobileAppswithJavaScript_Color Images.pdf
Trang 38Although we have taken every care to ensure the accuracy of our content,mistakes do happen If you find a mistake in one of our books-maybe a
mistake in the text or the code-we would be grateful if you could report this
to us By doing so, you can save other readers from frustration and help usimprove subsequent versions of this book If you find any errata, please
report them by visiting http://www.packtpub.com/submit-errata, selecting your book,clicking on the Errata Submission Form link, and entering the details of yourerrata Once your errata are verified, your submission will be accepted andthe errata will be uploaded to our website or added to any list of existingerrata under the Errata section of that title
To view the previously submitted errata, go to https://www.packtpub.com/books/conten t/support and enter the name of the book in the search field The required
information will appear under the Errata section
Trang 39Piracy of copyrighted material on the Internet is an ongoing problem acrossall media At Packt, we take the protection of our copyright and licenses veryseriously If you come across any illegal copies of our works in any form onthe Internet, please provide us with the location address or website nameimmediately so that we can pursue a remedy
Please contact us at copyright@packtpub.com with a link to the suspected piratedmaterial
We appreciate your help in protecting our authors and our ability to bring youvaluable content
Trang 40If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem