Mastering React Native
By Eric Masiello and Jacob Friedmann
5/5
()
About this ebook
- Apply flexbox to get layout and build rich animations that bring your React Native application to life
- Integrate third-party libraries and develop customized components that run natively on iOS and Android platforms
- Combine React Native with Redux, Redux middleware, and a remote API to build scalable data-driven applications
This book is for anyone who wants to build cross-platform native mobile applications using only JavaScript and the React Native framework. In particular, this book is especially useful for front-end developers who want to use their current skillset to build mobile applications. An existing working knowledge of JavaScript will help you get the most out of this book.
Related to Mastering React Native
Related ebooks
React Projects: Build 12 real-world applications from scratch using React, React Native, and React 360 Rating: 0 out of 5 stars0 ratingsReact and React Native Rating: 0 out of 5 stars0 ratingsReact.js Essentials Rating: 4 out of 5 stars4/5ReactJS by Example - Building Modern Web Applications with React Rating: 4 out of 5 stars4/5Web Development with MongoDB and NodeJS - Second Edition Rating: 0 out of 5 stars0 ratingsReact Components Rating: 0 out of 5 stars0 ratingsModern JavaScript Applications Rating: 0 out of 5 stars0 ratingsBuilding Scalable Apps with Redis and Node.js Rating: 0 out of 5 stars0 ratingsLearning Node.js for Mobile Application Development Rating: 0 out of 5 stars0 ratingsJavaScript at Scale Rating: 0 out of 5 stars0 ratingsDart By Example Rating: 0 out of 5 stars0 ratingsASP.NET Core 3 and React: Hands-On full stack web development using ASP.NET Core, React, and TypeScript 3 Rating: 0 out of 5 stars0 ratingsLearning ASP.NET Core MVC Programming Rating: 5 out of 5 stars5/5Node Web Development, Second Edition Rating: 0 out of 5 stars0 ratingsJump Start Vue.js Rating: 4 out of 5 stars4/5React Native By Example Rating: 0 out of 5 stars0 ratingsGetting Started with React Rating: 0 out of 5 stars0 ratingsGetting Started with React Native Rating: 4 out of 5 stars4/5React: Building Modern Web Applications Rating: 5 out of 5 stars5/5React Deep Dive Rating: 5 out of 5 stars5/5Hands-on React Native Rating: 1 out of 5 stars1/5Learn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/5Mastering React Test-Driven Development: Build rock-solid, well-tested web apps with React, Redux and GraphQL Rating: 0 out of 5 stars0 ratingsReact Design Patterns and Best Practices Rating: 0 out of 5 stars0 ratingsReact to Python: Creating React Front-End Web Applications with Python Rating: 0 out of 5 stars0 ratingsWeb Development with MongoDB and Node.js Rating: 0 out of 5 stars0 ratingsClean Code in JavaScript: Develop reliable, maintainable, and robust JavaScript Rating: 5 out of 5 stars5/5Node.js By Example Rating: 2 out of 5 stars2/5
Internet & Web For You
Principles of Web Design Rating: 0 out of 5 stars0 ratingsEverybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Get Into UX: A foolproof guide to getting your first user experience job Rating: 4 out of 5 stars4/5Stop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5Cybersecurity For Dummies Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5Coding For Dummies Rating: 5 out of 5 stars5/5The Logo Brainstorm Book: A Comprehensive Guide for Exploring Design Directions Rating: 4 out of 5 stars4/5The Basics of User Experience Design by Interaction Design Foundation Rating: 4 out of 5 stars4/5Explain the Cloud Like I’m 10 Rating: 5 out of 5 stars5/5RESTful API Design - Best Practices in API Design with REST: API-University Series, #3 Rating: 5 out of 5 stars5/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Learn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/5UX/UI Design Playbook Rating: 4 out of 5 stars4/52022 Adobe® Premiere Pro Guide For Filmmakers and YouTubers Rating: 5 out of 5 stars5/5The Designer’s Guide to Figma: Master Prototyping, Collaboration, Handoff, and Workflow Rating: 0 out of 5 stars0 ratingsClassic Computer Science Problems in Python Rating: 0 out of 5 stars0 ratingsToken Economy: How the Web3 reinvents the Internet Rating: 4 out of 5 stars4/5Sad by Design: On Platform Nihilism Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Deep Learning with Python Rating: 5 out of 5 stars5/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5
Reviews for Mastering React Native
2 ratings0 reviews
Book preview
Mastering React Native - Eric Masiello
Table of Contents
Mastering React Native
Credits
Disclaimer
About the Authors
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Building a Foundation in React
Library versus framework
Motivation for React
Getting started in React
Describing components in JSX
The component
Component composition
Props and PropTypes
Accepting props
PropTypes
Passing props
Default props
Props.children
Event handlers
State
The component lifecycle
The update cycle
Unmounting the component
Alternate component forms
React.createClass
Functional components
Summary
2. Saying HelloWorld in React Native
Understanding the mobile app development ecosystem
Adobe PhoneGap
Ionic
NativeScript
React Native
Extending React Native
Introducing style and layout in React Native
Understanding all the React Native tools
Xcode
Google Chrome
Homebrew (also known as brew)
Node.js and npm
Watchman
Flow
React Native command-line interface (CLI)
Installing our tools
Installing Xcode
Installing Homebrew
Installing Node and npm
Installing Watchman and Flow
Installing the React Native CLI
Creating our first React Native app
React Native Packager
Understanding our HelloWorld app
Importing dependencies using ECMAScript 2015
Our HelloWorld component
HelloWorld style code
Registering the root component
Why import React?
Debugging a React Native app
Enabling the Chrome Debugger
Breakpoints
Summary
3. Styling and Layout in React Native
Constructing and applying styles
Inline styles
Styles as objects in your React Native components
Stylesheet
Using Stylesheet.hairlineWidth
Applying component-specific style properties
Styling without inheritance
Understanding React Native's take on the box model and flexbox
Box model
Understanding Flexbox
Covering the other axis
Flex shrinking and growing
Setting flexBasis
Growing and shrinking flex items
Styling text with React Native
Text style properties
Encapsulating text styles in reusable components
Styling images
Background images
Inspecting and debugging styles
Using the React Native Inspector
Adding media query behavior to React Native
Using Dimensions
Using onLayout per View
Summary
4. Starting our Project with React Native Components
Native components
Text
Props
View
Props
Image
Props
Static methods
Touchable
Props
ListView
DataSource
renderRow
Props
Modal
Props
WebView
Props
TabBarIOS
Props
TabBarIOS.Item
Props
TextInput
Props
Other input components
Native APIs
ActionSheetIOS
Alert
Vibration
StatusBar
Summary
5. Flux and Redux
The Flux architecture
Motivation
Implementing Flux
Creating our view
Actions and action creators
Dispatcher
Stores
Rendering updated data
Getting started with Redux
Principles of Redux
Installing Redux
Implementing Redux
Refactoring the store
Reducer
Creating the store
Multiple reducers
Action creators
Subscribing to the store
React-Redux
Installing React-Redux
React context and providers
Container and presentational components
Middleware
Summary
6. Integrating with the NYT API and Redux
Understanding the NYT API data
Wiring up our Redux data flow
Creating the Redux state tree
Wiring up Redux data to our app
Refactoring and reshaping
Refactoring the components
Reshaping the data
Introducing Reselect
Adding search
Wiring up the NYT API with asynchronous requests
Fixing iOS transport security
Adding pull to refresh and a loading spinner
Summary
7. Navigation and Advanced APIs
Navigation landscape
NavigatorIOS
Navigator
NavigationExperimental
Choosing a navigator
Using Navigator
The Navigator component
Navigation bar
Advanced navigation with NavigationExperimental
Representing the navigation state
Managing the navigation state
The CardStack component
Navigation header
Tabbed navigation
Adding in the modal
Other advanced APIs
Offline messages with NetInfo
Opening the browser with linking
Saving bookmarks locally with AsyncStorage
Summary
8. Animation and Gestures in React Native
Introducing LayoutAnimation and Animated
Building the basic Onboarding experience
Getting started
Adding LayoutAnimation
Adding a bit more animation
Understanding Animated
Refactoring our Onboarding experience
Adding Animated to our Onboarding experience
Interpolating Animated Values
Using PanResponder with the Animated API
Touching up PanResponder
Summary
9. Refactoring for Android
Installing the necessary tools
Installing the Java Development Kit
Installing Android Studio
Configuring Android Studio
Configuring ANDROID_HOME and your PATH
Verifying that the CPU/ABIs are installed
Starting the Android emulator
Adding Android support to RNNYT
Branching platform logic
Refactoring RNNYT for Android
Fixing Android vibration
Using DrawerLayoutAndroid
Customizing Android styling
Enabling LayoutAnimation
Summary
10. Using and Writing Native Modules
Using native modules
Installing native modules
Using the library
Profile page
Adding the profile to the iOS home screen
Adding the profile to the Android home screen
Writing native modules
Native modules in iOS
Setting up the module
Exporting methods
Communicating with callbacks
Communicating with promises
Communicating with events
Exporting constants
Native modules in Android
Setting up the module
Exporting methods
Communicating with callbacks
Communicating with promises
Communicating with events
Exporting constants
Summary
11. Preparing for Production
Testing
Unit testing
Component testing
Performance
Problematic ListView
Using Perf Monitor
Analyzing a Systrace
The React Perf Library
shouldComponentUpdate and PureRenderMixin
Minimizing the impact of state changes
The ListView data source
Additional optimizations
Unresponsive touch and slow navigation
Mitigating unresponsive touch
Smoothing out animations with InteractionManager
Performance summary
Running on physical devices
Debugging on an iOS device
Testing your app on an iOS device using Release
Debugging on Android devices
Generating a signed APK
Deploying our application
Remove debugging code
iOS
Creating provisioning profiles
Registering an application in iTunes Connect
Adding icons and updating the launch screen
Creating an archive
Beta testing and release
Android
Signing the application
Testing the release build
Generating the APK
Beta-test and release
Summary
12. React Native Tools and Resources
Evaluating React Native Editors, Plugins, and IDEs
Atom and Nuclide
Taking React Native beyond iOS and Android
Introducing React Native Web
Configuring React Native Web
React Native plugin for Universal Windows Platform
Configuring the React Native plugin for UWP
React Native macOS
Configuring React Native macOS
Summary
References
Mastering React Native
Mastering React Native
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 the prior 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 in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this 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 this information.
First published: January 2017
Production reference: 1060117
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-578-5
www.packtpub.com
Credits
Disclaimer
We are using the New York Times' API for illustrative purposes only. We do not recommend you publish your application to the app store using this API without first reading the Terms of Use (https://developer.nytimes.com/tou). For more information please consult the NYT's terms and conditions.
About the Authors
Eric Masiello is a lead software engineer for Vistaprint Digital. Formerly, Eric worked as a principal frontend engineer for the Advisory Board Company and built mobile apps for the Education Advisory Board. Eric has worked primarily as a frontend/UI developer for over 10 years and freelances as a website designer/developer at http://www.synbydesign.com. He has taught frontend topics at General Assembly in Washington, D.C. and was a technical reviewer for Mastering ReactJS, a video by Packt Publishing.
You can follow him here:
https://www.linkedin.com/in/ericmasiello
https://twitter.com/ericmasiello
http://synbydesign.com
First and foremost, I must extend an enormous thank you to my beautiful, talented, and always-inspiring wife, Hyun. If not for her support, this book would honestly not exist. My deepest gratitude also goes out to my family: Mom, Dad, Brian, Juliana, Nicolas, Umma, and my sisters Hannah, Min, and Carroll. I’m truly blessed to have such a wonderful and supportive family. Shout out to all the inspiring people I’ve had the honor of working with over the years. I’ve learned so much from all of you. Thanks to Keith, Michael, Andrew, Scott, Shelley, Kelly, the inimitable Karthik, Jesse, Jaworski, Beth, Mat, Anbu, Ashwin, Kevin, Ann, all my PIC/RCS homies, the EAB dev/UI team, the entire ABC/EAB UX team, and finally my new Vistaprint Digital family. Thank you to all my close friends who have balanced me, challenged me, shared a drink, or just a laugh: Bryan, Alan, Chris, Kyril, Brandon, April, and the whole Expansion Broadcast + DC crew. Thank you to everyone at Packt for bringing me along on this amazing (and sleepless) journey. And finally, thanks to my coauthor Jacob for all the work he did in realizing this book and for agreeing to even write a book with someone he had known for all of two weeks.
Jacob Friedmann is a developer living in Seattle, WA. He has been working as a developer professionally for 5 years and is currently a principal software engineer at AddThis, an Oracle company. At AddThis, he works on large front and backend applications. He also builds mobile applications using React Native, including Audicy (http://audicy.io), which will soon be launched on the App Store. He has taught several classes, including frontend web development and JavaScript development through General Assembly in Washington D.C.
You can follow him here:
https://www.linkedin.com/in/jacob-friedmann
https://twitter.com/JacobDFriedmann
Writing a book (my first!) is hard, and I don’t think I would have been able to do it without the support of my loving boyfriend, Matt. He weathered my frequent complaining in stride and kept me focused when I needed it most. For that, I am incredibly grateful. Huge thanks to all of my AddThis family who have always inspired me to keep learning and pushed me to do my best work. To all of my friends and family, who were patient with me when I became a recluse to finish this project, thank you. You are loved, and I promise not to do this again for a while! Finally, to Eric for pulling me along on this adventure. I definitely didn’t know what I was getting myself into when I agreed to this, but I can’t imagine having a more dedicated and capable partner.
About the Reviewer
Patrick Puritscher began developing websites at the age of 14 by teaching himself the necessary skills. Already using React.js, he started to develop with React Native, shortly after watching the initial presentation. He is also active in the community with his open source components and recently published an app for iOS, completely written with React Native. After graduating with his bachelor’s degree, Patrick worked as the lead developer for multiple internally used web apps and a website with several million visits each month. It is his personal ambition to create software for people that makes their life easier, rather than making it more difficult with poor UX. Patrick has just started with his master’s degree in Business Informatics.
You can follow him on:
https://twitter.com/whoispurii
http://patrickpuritscher.com
www.PacktPub.com
For 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 [email protected] 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 and offers 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.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].
Preface
React Native is a library for creating mobile applications using familiar web technologies without sacrificing performance or the look and feel typically associated with fully native applications. It is built on top of Facebook’s open source JavaScript library, React, and indeed, iOS and Android applications created using the library are primarily written in JavaScript. Because one does not need to learn new languages, ecosystems, and best practices for each platform they work on, React Native is pushing the boundaries of what is possible for React developers.
In this book, we will look at the fundamental concepts of React and React Native, as well as the libraries and tools within the React Native ecosystem. We will also work towards the more practical goal of creating a complete React Native application. Finally, we’ll dig into useful and complex React Native concepts such as animation, navigation, native modules, testing and performance analysis. Upon turning over the last page of this book, you’ll be armed with the knowledge to create polished, sophisticated mobile applications using React Native.
What this book covers
Chapter 1, Building a Foundation in React, In order to work effectively in React Native, you must first understand React. This chapter explains the motivation behind React and teaches you how to think in React.
Chapter 2, Saying Hello World in React Native, contains two primary topics. First, we’ll review how React Native works and compare it to other popular mobile development options. Then, we’ll switch gears and focus on configuring your computer to build your first React Native project for iOS.
Chapter 3, Styling and Layout in React Native, React Native borrows many concepts from the web development world, including some of the best parts of Cascading Style Sheets (CSS). It also deliberately avoids some of CSS’s less desirable qualities. This chapter explains how to style React Native apps and how to use Flexbox to layout components.
Chapter 4, Starting our Project with React Native Components, React Native includes many powerful components and APIs. This chapter demonstrates how to use many of these as we begin to build our news reader app, called Readly.
Chapter 5, Flux and Redux, ... The React community has largely eschewed the Model View Controller pattern in favor of a unidirectional data flow pattern called Flux. In this chapter, we’ll help you think in Flux and explain how to leverage a popular Flux implementation known as Redux.
Chapter 6, Integrating with the NYT API and Redux, builds upon what we learned in this chapter. In order to bring our Readly app to life, we’ll implement Redux and Redux middleware as a means of managing our data and communicating with the New York Times API.
Chapter 7, Navigation & Advanced APIs, Navigation in React Native has been a long journey resulting in an abundance of navigation options. But which should you choose? This chapter will make sense of these options. We’ll then apply experimental navigation components along with other advanced React Native APIs to our project.
Chapter 8, Animation and Gestures in React Native, React Native offers two primary ways of creating fluid animations. This chapter will explain how to apply each of these along with touch gesture support to build out an on boarding experience for our Readly app.
Chapter 9, Refactoring for Android, React Native makes cross platform development simple. However, configuring your computer to actually build for Android is a bit less than simple. This chapter will walk you through, step by step, how to install and configure all the tools necessary for Android development. We’ll then revisit our project, refactoring it to both work and feel like a first class Android app.
Chapter 10, Using and Writing Native Modules, One of the most amazing parts of React Native is that it doesn’t limit you to the components and APIs that come packaged with the framework. If you want your app to do something else, you can either bridge custom native code to React Native or include other third-party libraries. This chapter adds additional capabilities to our project by exploring how to create custom native code written in Objective C for iOS and Java for Android.
Chapter 11, Preparing for Production, Discovering the root cause of bug or performance problem can be a real chore. In this chapter we’ll introduce Jest, a testing framework along with other tools for uncovering pesky performance problems. Finally, we’ll show you how to bundle your apps so you can ship them to the iOS and Android stores.
Chapter 12, React Native Tools & Resources, React Native is praised for its awesome developer experience and cross platform support. But can we take React Native even further? In this final chapter, we’ll show off some tools that can improve upon how you build React Native apps. Then we’ll explore a few React Native projects that allow us to extend platform support to the web, macOS, and even Windows.
What you need for this book
While we will add Android support to our project in later chapters, the majority of this book focuses on iOS development. In order to develop for iOS, you must have access to an Apple Mac computer capable of running Xcode 7 or later. Xcode is only necessary for building and testing React Native apps. You’re welcome to edit your code in any editor or IDE of your choosing.
In addition to Xcode, React Native requires a few other tools. These include Homebrew, Node.js (6.5.0 or later), npm (3.10.3 or later), Watchman, the React Native CLI, and Google Chrome for debugging. We’ll explain what all these tools are and how to install them in Chapter 2, Saying Hello World in React Native.
In Chapter 9, Refactoring for Android, we’ll update our project so it can run on both platforms. Android has its own set of software requirements including the Java Development Kit (JDK 1.8 or later) and Android Studio. Once again, we’ll walk you through how to install and configure these tools in Chapter 9, Refactoring for Android.
Finally, in Chapter 12, React Native Tools & Resources, we’ll evaluate software that can aid your React Native workflow and allow you to build React Native apps for even more platforms. All of these installations are completely optional. However, it’s worth noting that the React Native plugin for Universal Windows Platform will require a computer or virtual machine running Windows 10 and Visual Studio 2015 Community.
Who this book is for
It’s expected the reader possess a strong understanding of JavaScript and is familiar with ECMAScript 2015 (ES2015 or ES6). Code samples in this book will heavily leverage ES2015 features such as classes, arrow functions, destructuring, and spreading. Familiarity with React, mobile development, HTML, and CSS will aid in your understanding but are not a requirement.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.
A block of code is set as follows:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf
New 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.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about 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 [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading 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:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder 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/PacktPublishing/Mastering-React-Native. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Errata
Although 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 us improve 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 your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Chapter 1. Building a Foundation in React
There is a common trope within the frontend web development community that boils down to new day, new framework. It is a comment on the velocity at which this profession is changing and evolving. The rapid pace can be exhausting, but it is also exciting because of what it represents. The domain of frontend developers seems to be ever expanding-from simple web pages to web applications, mobile applications, and beyond-and with that, the number of smart people contributing ideas and code to the collective knowledge bank is also expanding.
With all of that said, any sane person must pick and choose which developments to tune into. When React.js emerged on to the open source scene in May 2013 from the inner-sanctum of Facebook, it would have been easy to brush this library off as just another frontend library. That, however, would have been a mistake. It could be said that React was the most significant and influential open source development in frontend technology in recent memory. Its growth beyond the web and its application in the realm of mobile development through React Native is both a testament to its popularity and a boon to its potential utility.
React Native is a library for creating native mobile applications using familiar web technologies that is built on top of React. What this means is that in order to understand React Native, we must first explore React. In this chapter, we'll examine the fundamentals of React. First, we'll talk briefly about the circumstances that led to React being created. We'll also cover these React concepts:
JSX, a JavaScript/HTML hybrid that we use to describe React components
React components
Component composition
Component properties, or props
Handling events
Component state
The React component lifecycle
Alternate component forms
Note
A note to the reader: this chapter focuses on React for the web, the original purpose of the library. This provides important context for the remainder of the book. If you already know React for the web, then it is probably safe to skip this chapter and proceed to Chapter 2, Saying Hello World in React Native.
Library versus framework
When people describe React, they often eschew the description of framework-a description often used for something such as Backbone or Angular-in favor of library. The reason for this more lightweight description is that React is not a complete solution for application development. It is often relegated to only a view-layer solution, and that characterization is mostly correct. React has some mechanisms for maintaining internal state, but it has no opinion about or solutions for data flow and management, server communication, routing, or other common frontend application concerns.
React, therefore, is often coupled with some other library or libraries to create a fully fleshed out application. The most common pairing is with an application architecture that is also the brainchild of the wizards at Facebook called Flux. Flux is not a library in and of itself; it is a set of design patterns that have been implemented by many different libraries, which will be discussed in more depth in Chapter 5, Flux and Redux.
Motivation for React
React and the community, libraries, and patterns that surround it are very much a reaction (pun intended) to some of the most frustrating and prevalent issues that plague JavaScript applications as they grow in size and complexity. JavaScript was not designed for creating large applications; it was designed, famously, in just 10 days as a scripting language to add a modicum of interactivity to lifeless web pages.
Chief among these concerns is the unpredictability that comes with shared mutable state. Historically, passing around JavaScript objects that represent the application's state to different views and controllers has been common practice. The ease with which those objects can be mutated by a rogue view, wisdom notwithstanding, can lead to hard-to-diagnose bugs, especially as applications and teams grow.
The foundational building block in a React application is the component, which is a declarative description of some visual feature on the page, such as a form or a menu. The declarative nature of components promotes predictability: given some set of external inputs (properties), the output is well defined and deterministic.
React also aims to combat one of the hurdles to writing efficient applications: the Document Object Model (DOM) is notoriously slow. If changes to the DOM are relatively infrequent, this may not be a problem, but in a complex application the time it takes to alter and redraw the DOM can add up. This is especially true for applications that take a declarative approach as React does, which necessitates re-rendering whenever the application's state changes.
The solution proposed by the React framework is to keep a representation of the DOM in memory, called a virtual DOM, and make all alterations there. Once the alterations have been made in memory, React can apply the minimum number of changes necessary to reconcile the real DOM with the virtual DOM. This also can allow quickly successive changes to be batched for greater efficiency. Taking this approach can lead to great gains in performance that can be noticed by end users.
In addition to solving some of the common problems faced when creating JavaScript applications, React components are modular and emphasize composition over inheritance, which makes code immensely reusable and testable. Additionally, a React component often has rendering logic, markup declaration, and even styles in the same file, which promotes the portability of code and the ability to write shared libraries of components.
Perhaps the most compelling reason to use React and React Native is the astounding amount of community adoption that has taken place in the last two years. People are excited about this technology, and rightly so; it is a novel approach to developing frontend applications that is, by most accounts, accelerating the development time on teams that choose to adopt it. With React Native, the idealistic promise of learn once, write anywhere is becoming more and more viable.
Getting started in React
To begin creating an interface in React, the first thing we need to do is break down the interface into conceptual components. We start with a large component, for instance, a news feed. We then say our large component is made up of, or composed of, other smaller components. In the case of our news feed, these smaller components might be individual news items. Each news item, in turn, might be composed of several even smaller components, such as images, a description,