41,99 €
Develop real world Android and iOS applications with the power of React native.
This book is for developers who want to use their JavaScript knowledge for mobile development. Prior knowledge of React will be beneficial.
Considering the success of the React framework, Facebook recently introduced a new mobile development framework called React Native. With React Native's game-changing approach to hybrid mobile development, you can build native mobile applications that are much more powerful, interactive, and faster by using JavaScript
This project-based guide takes you through eight projects to help you gain a sound understanding of the framework and helps you build mobile apps with native user experience. Starting with a simple standalone groceries list app, you will progressively move on to building advanced apps by adding connectivity with external APIs, using native features, such as the camera or microphone, in the mobile device, integrating with state management libraries such as Redux or MobX, or leveraging React Native's performance by building a full-featured game.
This book covers the entire feature set of React Native, starting from the simplest (layout or navigation libraries) to the most advanced (integration with native code) features.
By the end of this book, you'll be able to build professional Android and iOS applications using React Native.
This project-based guide consists of 8 projects. Each project is a standalone project that covers the core techniques and concepts in each project.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 267
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
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, 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: November 2017
Production reference: 1061117
ISBN 978-1-78728-809-6
www.packtpub.com
Author
Emilio Rodriguez Martinez
Copy Editor
Charlotte Carneiro
Reviewers
Mike Grabowski
Christoph Michel Alessandro Molina
Project Coordinator
Sheejal Shah
Acquisition Editor
Reshma Raman
Proofreader
Safis Editing
Content Development Editor
Jason Pereira
Indexer
Rekha Nair
Technical Editor
Prajakta Mhatre
Production Coordinator
Melwyn D'sa
Emilio Rodriguez Martinez is a senior software engineer who has been working on highly demanding JavaScript projects since 2010. He transitioned from web development positions into mobile development, first with hybrid technologies such as Cordova and then with native JavaScript solutions such as Titanium.In 2015, he focused on the development and maintenance of several apps built in React Native, some of which were featured in Apple's App Store as the top apps of the week. Nowadays, Emilio is part of the Red Hat mobile team, which leverages Red Hat's open source mobile platform. He serves as an advocate for mobile developers using RHMAP. He is also an active contributor to React Native's codebase and StackOverflow, where he provides advice on React and React Native questions.
Mike Grabowski is a CTO and co-founder of Callstack (callstack.com), a consultancy that helps developers and businesses launch their apps for everyone, on many platforms, at the same time. Right now, it is done with the help of React Native. He is also on a React Native core team where he helps to orchestrate monthly releases of the framework. At Callstack, he does a whole bunch of open source activities for the community, including React Native EU--the first conference to focus on React Native in the world. When not working, he enjoys driving his BMW on a race track.
Christoph Michel is a software engineer who's been involved with React Native since its early release in 2015. He has published several React Native apps on the App Store. He also develops open source components and writes technical articles on cmichel.io.
Alessandro Molina, partner at AXANT.it, a software engineer at Crunch.IO, and a father of two, has been passionate about web and mobile development for the past 15 years. He is particularly involved in the Python community and is the author of the DukPy project, which runs React and JavaScript in pure Python environments. He is also a core developer of the TurboGears2 Python Web Framework and co-maintainer of widely used web development libraries and technologies in Python and MongoDB environments such as the Beaker Session and Caching framework and the Ming MongoDB ODM.
He was also the original author of the AXMEAS hybrid multiplatform mobile development framework, which is used to create mobile apps that run on iOS, Android, Windows, and on other browsers. In his spare time, Alessandro enjoys exploring big data and machine learning solutions applied to nearly real-time use cases and traveling with his family to learn new things, not only about software but about the world and culture too.
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.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787288099.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
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
Downloading the color images of this book
Errata
Piracy
Questions
Shopping List
Overview
Setting up our project
Setting up the folder structure
Adding a Navigation component
Styling our app with NativeBase
Building the ShoppingList screen
Adding state to our screen
Adding event handlers
Putting it all together
Building the AddProduct screen
Using AsyncStorage
Adding state to our screen
Adding event listeners
Putting it all together
Installing and distributing the app
Testflight
Diawi
Installr
Summary
RSS Reader
Overview
Setting up the folder structure
Adding dependencies
Using vector icons
Managing our state with MobX
The store
Setting up the store
Defining actions
Networking in React Native
Creating our app's entry point
Building the FeedsList screen
Adding event handlers
Building the AddFeed screen
ActivityIndicator
Building the FeedDetail screen
Building the EntryDetail screen
Summary
Car Booking App
Overview
Setting up the folder structure
Files and folders created by React Native's CLI
__tests__/
android/ and ios/
node_modules/
Files in the root folder
react-native link
Running the app in the simulator
The developer menu
Creating our app's entry point
Adding images to our app
LocationSearch
Aligning elements
LocationPin
flexDirection
Dimensions
Shadows
ClassSelection
Adding custom fonts
Animations
ConfirmationModal
Summary
Image Sharing App
Overview
Setting up the folder structure
Redux
ImagesList
Gallery
Header
ActivityIndicator
Camera
MyImages
ImageGrid
Actions
Reducers
API
Summary
Guitar Tuner
Overview
Setting up the folder structure
Writing the native module
index.ios.js
utils
Tuner
Strings
Adding an icon
Adding a launch screen
Disabling the landscape mode
Summary
Messaging App
Overview
Firebase
Real-time database
Reading data from Firebase's database
Updating data in Firebase's database
Authentication
Setting up the folder structure
Users store
Chats store
Push notifications using Firebase
Login
Chats
ListItem
Chat
Search
Profile
Summary
Game
Overview
Sprites
Numbers
Background
Ground
Rocks
Parrot
The home screen
Game over screen
Setting up the folder structure
GameContainer
Actions
Reducer
The sprites module
The sprites array
prepareNewRockSizes()
getRockProps()
moveSprites()
bounceParrot()
checkForCollision()
getUpdatedScore()
Constants
Parrot
RockUp and RockDown
Ground
Score
Start
GameOver
StartAgain
Summary
E-Commerce App
Overview
Setting up the folder structure
Linting and code formatting
Indexes and main files
Reducers
API
ProductList
ProductDetail
MyCart
Payment
PaymentConfirmation
MyProfile
LoginOrRegister
Login
Register
Sales
Summary
React Native helps web and mobile developers to build apps for iOS and Android apps that perform at the same level as any other natively developed app. The range of apps that can be built using this library is huge. From e-commerce to games, React Native is a good fit for any mobile project due to its flexibility and extendable nature. It has good performance, reuses React knowledge, has the ability to import npm packages, and uses the same codebase for iOS and Android. There's no doubt React Native is not only a good alternative to native development, but also a great way to introduce web developers to a mobile project. This book aims to give JavaScript and React developers a peek at how some of the most popular apps in the market could be built from scratch with React Native. We will build all the apps in iOS and Android, except for those cases where the apps only make sense on one of the platforms.
Chapter 1, Shopping List, shows how a groceries list can be built in React Native using simple navigation and introducing some of the most common native components.
Chapter 2, RSS Reader, teaches you how to create a news feed reader using RSS.
Chapter 3, Car Booking App, explains how some of the most popular car-sharing apps could have been developed using React Native.
Chapter 4, Image Sharing App, teaches you the fundamentals of how a social network based on image sharing can be created with React Native.
Chapter 5, Guitar Tuner, is one of the apps that require components not yet available in React Native. We will build one of these native components and use it from a React Native app.
Chapter 6, Messaging App, 1:1 messaging apps are the most popular apps in the stores. In this chapter, we will build a full-featured messaging app including push notifications and cloud-based storage.
Chapter 7, Game, is fun and shows you the fundamentals of how a 2D game can be developed using React Native.
Chapter 8, E-Commerce App, uses React Native to build one of the most requested types of app in the market: an e-commerce app to buy and sell products online.
Most of the apps built throughout this book will run on Android and iOS, so a computer running Linux, Windows, or OSX will be required, although we recommend any Apple computer (running OSX 10 or later) to run both mobile platforms at once, as some examples will require working on XCode, which is only installable on OSX.
Other pieces of software we will use in examples are:
XCode
Android Studio
A React-ready IDE (such as Atom, VS Code, and SublimeText)
And of course, we will need React Native and React Native CLI installed (https://facebook.github.io/react-native/docs/getting-started.html).
This book is targeted at JavaScript developers trying to understand how different kinds of apps can be built using React Native. They will find a set of best practices and proven architectural strategies that can be applied to building any kind of app.
Although some basic concepts of React won't be explained in this book, no specific React skills are needed to follow along, since we won't dive deep into complex React patterns.
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 have to create an src folder where we will store all our React code."
Also in big code blocks, when some pieces of code are not relevant or reviewed in a different place, they will be replaced by an ellipsis (...).
A block of code is set as follows:
/*** index.js ***/import { AppRegistry } from 'react-native';import App from './src/main';AppRegistry.registerComponent('GroceriesList', () => App);
Any command-line input or output is written as follows:
react-native run-ios
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: "The back button on the Add a product screen."
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 to us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [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.
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.
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/React-Native-Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ReactNativeBlueprints_ColorImages.pdf.
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 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.
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.
Most of the modern languages and frameworks used to present a to-do list as their sample app. It is a great way to understand the basics of a framework as user interaction, basic navigation, or how to structure code. We'll start in a more pragmatic way: building a shopping list app.
You will be able to develop this app in React Native code, build it for both iOS and Android, and finally install it on your phone. This way, you could not only show your friends what you built, but also understand missing features that you can build by yourself, thinking about user-interface improvements, and above all, motivating yourself to keep learning React Native as you feel its true potential.
By the end of this chapter, you will have built a fully-functional shopping list that you can use on your phone and will have all the tools you need to create and maintain simple stateful apps.
One of the most powerful features of React Native is its cross-platform capabilities; we will build our shopping list app for both iOS and Android, reusing 99% of our code. Let's take a look at how the app will look on both platforms:
iOS:
After adding more products, this is how it will look:
Android:
After adding more products, this is how it will look:
The app will have a very similar user interface on both platforms, but we won't need to care much about the differences (for example, the back button on the Add a product screen), as they will be handled automatically by React Native.
It is important to understand that each platform has its own user interface patterns, and it's a good practice to follow them. For example, navigation is usually handled through tabs in iOS while Android prefers a drawer menu, so we should build both navigation patterns if we want happy users on both platforms. In any case, this is only a recommendation, and any user interface pattern could be built on every platform. In later chapters, we will see how to handle two different patterns in the most effective way within the same codebase.
The app comprises of two screens: your shopping list and a list of the products which could be added to your shopping list. The user can navigate from the Shopping List screen to the Add a product screen through the round blue button and back through the < Back button. We will also build a clear button in the shopping list screen (the round red button) and the ability to add and remove products on the Add a product screen.
We will be covering the following topics in this chapter:
Folder structure for a basic React Native projectReact Native's basic CLI commandsBasic navigationJS debuggingLive reloadingStyling with NativeBaseListsBasic state managementHandling eventsAsyncStoragePrompt popupsDistributing the appReact Native has a very powerful CLI that we will need to install to get started with our project. To install, just run the following command in your command line (you might need to run this with sudo), if you don't have enough permissions:
npm install -g react-native-cli
Once the installation is finished, we can start using the React Native CLI by typing react-native. To start our project, we will run the following command:
react-native init --version="0.49.3"
GroceriesList
This command will create a basic project named GroceriesList with all the dependencies and libraries you need to build the app on iOS and Android. Once the CLI has finished installing all the packages, you should have a folder structure similar to this:
The entry file for our project is index.js. If you want to see your initial app running on a simulator, you can use React Native's CLI again:
react-native run-ios
Or
react-native run-android
Provided you have XCode or Android Studio and Android Simulator installed, you should be able to see a sample screen on your simulator after compilation:
We have everything we need to set up to start implementing our app, but in order to easily debug and see our changes in the simulator, we need to enable two more features: remote JS debugging and live reloading.
For debugging, we will use React Native Debugger, a standalone app, based on the official debugger for React Native, which includes React Inspector and Redux DevTools. It can be downloaded following the instructions on its GitHub repository (https://github.com/jhen0409/react-native-debugger). For this debugger to work properly, we will need to enable Remote JS Debugging from within our app by opening a React Native development menu within the simulator by pressing command + ctrl + Z on iOS or command + M on Android.
If everything goes well, we should see the following menu appear:
Now, we will press two buttons: Debug Remote JS and Enable Live Reload. Once we are done with this, we have all our development environment up and ready to start writing React code.
Our app only comprises of two screens: Shopping List and Add Products. Since the state for such a simple app should be easy to manage, we won't add any library for state management (for example, Redux), as we will send the shared state through the navigation component. This should make our folder structure rather simple:
We have to create an src folder where we will store all our React code. The self-created file index.js will have the following code:
/*** index.js ***/import { AppRegistry } from 'react-native';import App from './src/main';AppRegistry.registerComponent('GroceriesList', () => App);
In short, these files will import the common root code for our app, store it in a variable named App and later pass this variable to the AppRegistry through the registerComponent method. AppRegistry is the component to which we should register our root components. Once we do this, React Native will generate a JS bundle for our app and then run the app when it's ready by invoking AppRegistry.runApplication.
Most of the code we will be writing, will be placed inside the src folder. For this app, we will create our root component (main.js) in this folder, and a screens subfolder, in which we will store our two screens (ShoppingList and AddProduct).
Now let's install all the initial dependencies for our app before continue coding. In our project's root folder, we will need to run the following command:
npm install
Running that command will install all the basic dependencies for every React Native project. Let's now install the three packages we will be using for this specific app:
npm install
native-base --save
npm install react-native-prompt-android --save
npm install react-navigation --save
Further ahead in this chapter, we will explain what each package will be used for.
React Native includes a powerful way to style our components and screens using Flexbox and a CSS-like API but, for this app, we want to focus on the functionality aspect, so we will use a library including basic styled components as buttons, lists, icons, menus, forms, and many more. It can be seen as a Twitter Bootstrap for React Native.
There are several popular UI libraries, NativeBase and React Native elements being the two most popular and best supported. Out of these two, we will choose NativeBase, since it's documentation is slightly clearer for beginners.
You can find the detailed documentation on how NativeBase works on their website (https://docs.nativebase.io/), but we will go through the basics of installing and using some of their components in this chapter. We previously installed native-base as a dependency of our project through npm install but NativeBase includes some peer dependencies, which need to be linked and included in our iOS and Android native folders. Luckily, React Native already has a tool for finding out those dependencies and linking them; we just need to run:
react-native link
At this point, we have all the UI components from NativeBase fully available in our app. So, we can start building our first screen.
All the interaction with the user will happen through event handlers in React Native. Depending on the controller, we will have different events which can be triggered. The most common event is onPress, as it will be triggered every time we push a button, a checkbox, or a view in general. Let's add some onPress handlers for all the components which can be pushed in our screen:
/*** ShoppingList.js ***/...render() { return ( <Container> <Content> <List> {this.state.products.map(p => {
