React Native
Notes for Professionals
React Native
Notes for Professionals
80+ pages
of professional hints and tricks
GoalKicker.com
Free Programming Books
Disclaimer
This is an unocial free book created for educational purposes and is
not aliated with ocial React Native group(s) or company(s).
All trademarks and registered trademarks are
the property of their respective owners
Contents
About
...................................................................................................................................................................................
1
Chapter 1: Getting started with React Native
................................................................................................
2
Section 1.1: Setup for Mac
Section 1.2: Setup for Linux (Ubuntu)
Section 1.3: Setup for Windows
.............................................................................................................................................
2
..........................................................................................................................
8
..................................................................................................................................
10
Chapter 2: Hello World
.............................................................................................................................................
12
Section 2.1: Editing index.ios.js or index.android.js
Section 2.2: Hello world!
..............................................................................................................................................
12
...................................................................................................
12
Chapter 3: Props
..........................................................................................................................................................
13
Section 3.1: PropTypes
Section 3.2: What are props?
Section 3.3: Use of props
Section 3.4: Default Props
................................................................................................................................................
13
.....................................................................................................................................
14
............................................................................................................................................
..........................................................................................................................................
14
15
Chapter 4: Multiple props rendering
Section 4.1: render multiple variables
................................................................................................................
16
........................................................................................................................
16
Chapter 5: Modal
........................................................................................................................................................
17
Section 5.1: Modal Basic Example
Section 5.2: Transparent Modal Example
..............................................................................................................................
17
.................................................................................................................
18
Chapter 6: State
..........................................................................................................................................................
20
Section 6.1: setState
Section 6.2: Initialize State
.....................................................................................................................................................
20
..........................................................................................................................................
22
Chapter 7: Routing
.....................................................................................................................................................
23
Section 7.1: Navigator component
.............................................................................................................................
23
Chapter 8: Styling
.......................................................................................................................................................
24
Section 8.1: Conditional Styling
Section 8.2: Styling using inline styles
Section 8.3: Styling using a stylesheet
Section 8.4: Adding multiple styles
..................................................................................................................................
.......................................................................................................................
......................................................................................................................
24
............................................................................................................................
Chapter 9: Layout
Section 9.1: Flexbox
.......................................................................................................................................................
......................................................................................................................................................
26
Chapter 10: Components
.........................................................................................................................................
35
Section 10.1: Basic Component
Section 10.2: Stateful Component
Section 10.3: Stateless Component
...................................................................................................................................
..............................................................................................................................
............................................................................................................................
35
Chapter 11: ListView
...................................................................................................................................................
37
Section 11.1: Simple Example
.......................................................................................................................................
37
Chapter 12: RefreshControl with ListView
......................................................................................................
38
Section 12.1: Refresh Control with ListView Full Example
Section 12.2: Refresh Control
Section 12.3: onRefresh function Example
.....................................................................................................................................
................................................................................................................
........................................................................................
38
Chapter 13: WebView
................................................................................................................................................
41
Section 13.1: Simple component using webview
Chapter 14: Command Line Instructions
.......................................................................................................
41
........................................................................................................
Section 14.1: Check version installed
Section 14.2: Initialize and getting started with React Native project
..........................................................................................................................
....................................................................
42
24
24
24
26
35
35
39
39
42
42
Section 14.3: Upgrade existing project to latest RN version
Section 14.4: Add android project for your app
Section 14.5: Logging
Section 14.6: Start React Native Packager
Publicité
..................................................................................................................................................
...............................................................................................................
...................................................................................
42
.......................................................................................................
Chapter 15: HTTP Requests
...................................................................................................................................
44
Section 15.1: Using Promises with the fetch API and Redux
Section 15.2: HTTP with the fetch API
Section 15.3: Networking with XMLHttpRequest
Section 15.4: WebSockets
Section 15.5: Http with axios
Section 15.6: Web Socket with Socket.io
....................................................................................
44
........................................................................................................................
.......................................................................................................
...........................................................................................................................................
.......................................................................................................................................
....................................................................................................................
Chapter 16: Platform Module
................................................................................................................................
49
Section 16.1: Find the OS Type/Version
.....................................................................................................................
49
Chapter 17: Images
....................................................................................................................................................
50
Section 17.1: Image Module
Section 17.2: Image Example
Section 17.3: Conditional Image Source
Section 17.4: Using variable for image path
Section 17.5: To fit an Image
Chapter 18: Custom Fonts
.........................................................................................................................................
......................................................................................................................................
....................................................................................................................
.............................................................................................................
50
......................................................................................................................................
......................................................................................................................................
Section 18.1: Custom fonts for both Android and IOS
Section 18.2: Steps to use custom fonts in React Native (Android)
Section 18.3: Steps to use custom fonts in React Native (iOS)
..............................................................................................
.......................................................................
53
...............................................................................
53
Chapter 19: Animation API
......................................................................................................................................
56
Section 19.1: Animate an Image
.................................................................................................................................
56
Chapter 20: Android - Hardware Back Button
............................................................................................
57
Section 20.1: Detect Hardware back button presses in Android
Section 20.2: Example of BackAndroid along with Navigator
Section 20.3: Hardware back button handling using BackHandler and Navigation Properties (without
...............................................................................
............................................................................
57
57
using deprecated BackAndroid & deprecated Navigator)
.............................................................................
58
Section 20.4: Example of Hardware back button detection using BackHandler
.................................................
59
Chapter 21: Run an app on device (Android Version)
..............................................................................
60
Section 21.1: Running an app on Android Device
.....................................................................................................
60
Chapter 22: Native Modules
..................................................................................................................................
61
Section 22.1: Create your Native Module (IOS)
........................................................................................................
61
Chapter 23: Linking Native API
Section 23.1: Outgoing Links
Section 23.2: Incomming Links
.............................................................................................................................
63
.......................................................................................................................................
...................................................................................................................................
Chapter 24: ESLint in React Native
...................................................................................................................
65
Section 24.1: How to start
...........................................................................................................................................
65
Chapter 25: Integration with Firebase for Authentication
....................................................................
66
Section 25.1: Authentication In React Native Using Firebase
Section 25.2: React Native - ListView with Firebase
..................................................................................
66
................................................................................................
66
Chapter 26: Navigator Best Practices
..............................................................................................................
69
...............................................................................................................................................
69
Section 26.1: Navigator
Section 26.2: Use react-navigation for navigation in react native apps
Section 26.3: react-native Navigation with react-native-router-flux
Chapter 27: Navigator with buttons injected from pages
...............................................................
71
.....................................................................
....................................................................
42
43
43
44
45
45
45
47
50
50
50
51
52
52
63
63
72
74
Section 27.1: Introduction
Section 27.2: Full commented example
............................................................................................................................................
74
....................................................................................................................
74
Chapter 28: Create a shareable APK for android
......................................................................................
77
Section 28.1: Create a key to sign the APK
Section 28.2: Once the key is generated, use it to generate the installable build:
Section 28.3: Generate the build using gradle
Section 28.4: Upload or share the generated APK
.........................................................................................................
..................................................................................................
Publicité
77
77
...............................................................................................................
77
...............................................
77
Chapter 29: PushNotification
................................................................................................................................
78
Section 29.1: Push Notification Simple Setup
Section 29.2: Navigating to scene from Notification
............................................................................................................
78
...............................................................................................
80
Chapter 30: Render Best Practises
....................................................................................................................
82
Section 30.1: Functions in JSX
....................................................................................................................................
82
Chapter 31: Debugging
.............................................................................................................................................
83
Section 31.1: Start Remote JS Debugging in Android
Section 31.2: Using console.log()
..............................................................................................
83
................................................................................................................................
83
Chapter 32: Unit Testing
.........................................................................................................................................
84
Section 32.1: Unit Test In React Native Using Jest
...................................................................................................
84
Credits
..............................................................................................................................................................................
85
You may also like
........................................................................................................................................................
87
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/ReactNativeBook
This React Native Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official React Native group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to [email protected]
GoalKicker.com – React Native Notes for Professionals
1
Chapter 1: Getting started with React
Native
Section 1.1: Setup for Mac
Installing package manager Homebrew brew
Paste that at a Terminal prompt.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Installing Xcode IDE
Download it using link below or find it on Mac App Store
https://developer.apple.com/download/
NOTE: If you have Xcode-beta.app installed along with production version of Xcode.app, make sure you
are using production version of xcodebuild tool. You can set it with:
sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer/
Installing Android environment
Git git
*If you have installed XCode, Git is already installed, otherwise run the following
brew install git
Latest JDK
Android Studio
Choose a Custom installation
GoalKicker.com – React Native Notes for Professionals
2
Choose both Performance and Android Virtual Device
GoalKicker.com – React Native Notes for Professionals
3
After installation, choose Configure -> SDK Manager from the Android Studio welcome window.
GoalKicker.com – React Native Notes for Professionals
4
In the SDK Platforms window, choose Show Package Details and under Android 6.0 (Marshmallow), make
sure that Google APIs, Intel x86 Atom System Image, Intel x86 Atom_64 System Image, and Google APIs Intel
x86 Atom_64 System Image are checked.
GoalKicker.com – React Native Notes for Professionals
5
In the SDK Tools window, choose Show Package Details and under Android SDK Build Tools, make sure that
Android SDK Build-Tools 23.0.1 is selected.
GoalKicker.com – React Native Notes for Professionals
6
Environment Variable ANDROID_HOME
Ensure the ANDROID_HOME environment variable points to your existing Android SDK. To do that, add this
to your ~/.bashrc, ~/.bash_profile (or whatever your shell uses) and re-open your terminal:
If you installed the SDK without Android Studio, then it may be something like: /usr/local/opt/android-sdk
export ANDROID_HOME=~/Library/Android/sdk
Dependencies for Mac
You will need Xcode for iOS and Android Studio for android, node.js, the React Native command line tools, and
Watchman.
We recommend installing node and watchman via Homebrew.
brew install node
brew install watchman
Watchman is a tool by Facebook for watching changes in the filesystem. It is highly recommended you
install it for better performance. It is optional.
Node comes with npm, which lets you install the React Native command line interface.
npm install -g react-native-cli
If you get a permission error, try with sudo:
sudo npm install -g react-native-cli.
For iOS the easiest way to install Xcode is via the Mac App Store. And for android download and install Android
Studio.
If you plan to make changes in Java code, we recommend Gradle Daemon which speeds up the build.
Testing your React Native Installation
Use the React Native command line tools to generate a new React Native project called "AwesomeProject", then run
react-native run-ios inside the newly created folder.
react-native init AwesomeProject
cd AwesomeProject
react-native run-ios
You should see your new app running in the iOS Simulator shortly. react-native run-ios is just one way to run your
app - you can also run it directly from within Xcode or Nuclide.
Modifying your app
Now that you have successfully run the app, let's modify it.
Open index.ios.js or index.android.js in your text editor of choice and edit some lines.
GoalKicker.com – React Native Notes for Professionals
7
Hit Command⌘ + R in your iOS Simulator to reload the app and see your change! That's it!
Congratulations! You've successfully run and modified your first React Native app.
source: Getting Started - React-Native
Section 1.2: Setup for Linux (Ubuntu)
1) Setup Node.JS
Start the terminal and run the following commands to install nodeJS:
curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
sudo apt-get install nodejs
If node command is unavailable
sudo ln -s /usr/bin/nodejs /usr/bin/node
Alternatives NodeJS instalations:
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
or
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs
check if you have the current version
node -v
Run the npm to install the react-native
sudo npm install -g react-native-cli
2) Setup Java
sudo apt-get install lib32stdc++6 lib32z1 openjdk-7-jdk
3) Setup Android Studio:
Android SDK or Android Studio
Publicité
http://developer.android.com/sdk/index.html
Android SDK e ENV
export ANDROID_HOME=/YOUR/LOCAL/ANDROID/SDK
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
4) Setup emulator:
On the terminal run the command
android
Select "SDK Platforms" from within the SDK Manager and you should see a blue checkmark next to "Android 7.0
GoalKicker.com – React Native Notes for Professionals
8
(Nougat)". In case it is not, click on the checkbox and then "Apply".
5) Start a project
Example app init
react-native init ReactNativeDemo && cd ReactNativeDemo
Obs: Always check if the version on android/app/build.gradle is the same as the Build Tools downloaded on
your android SDK
android {
compileSdkVersion XX
buildToolsVersion "XX.X.X"
...
6) Run the project
Open Android AVD to set up a virtual android. Execute the command line:
android avd
Follow the instructions to create a virtual device and start it
Open another terminal and run the command lines:
react-native run-android
GoalKicker.com – React Native Notes for Professionals
9
react-native start
Section 1.3: Setup for Windows
Note: You cannot develop react-native apps for iOS on Windows, only react-native android apps.
The official setup docs for react-native on windows can be found here. If you need more details there is a granular
guide here.
Tools/Environment
Windows 10
command line tool (eg Powershell or windows command line)
Chocolatey (steps to setup via PowerShell)
The JDK (version 8)
Android Studio
An Intel machine with Virtualization technology enabled for HAXM (optional, only needed if you want to use
an emulator)
1) Setup your machine for react native development
Start the command line as an administrator run the following commands:
choco install nodejs.install
choco install python2
Restart command line as an administrator so you can run npm
npm install -g react-native-cli
After running the last command copy the directory that react-native was installed in. You will need this for Step 4. I
tried this on two computers in one case it was: C:\Program Files (x86)\Nodist\v-x64\6.2.2. In the other it was:
C:\Users\admin\AppData\Roaming\npm
2) Set your Environment Variables
A Step by Step guide with images can be found here for this section.
Open the Environment Variables window by navigating to:
[Right click] "Start" menu -> System -> Advanced System Settings -> Environment Variables
In the bottom section find the "Path" System Variable and add the location that react-native was installed to in step
1.
If you haven't added an ANDROID_HOME environment variable you will have to do that here too. While still in the
"Environment Variables" window, add a new System Variable with the name "ANDROID_HOME" and value as the
path to your android sdk.
Then restart the command line as an admin so you can run react-native commands in it.
3) Create your project In command line, navigate to the folder you want to place your project and run the
following command:
react-native init ProjectName
GoalKicker.com – React Native Notes for Professionals
10
4) Run your project Start an emulator from android studio Navigate to the root directory of your project in
command line and run it:
cd ProjectName
react-native run-android
You may run into dependency issues. For example, there may be an error that you do not have the correct build
tools version. To fix this you will have to open the sdk manager in Android Studio and download the build tools
from there.
Congrats!
To refresh the ui you can press the r key twice while in the emulator and running the app. To see developer options
you can press ctrl + m.
GoalKicker.com – React Native Notes for Professionals
11
Chapter 2: Hello World
Section 2.1: Editing index.ios.js or index.android.js
Open index.ios.js or index.android.js and delete everything between the <View> </View>. After that, write
<Text> Hello World! </Text> and run the emulator.
You should see Hello World! written on the screen!
Congrats! You've successfully written your first Hello World!
Section 2.2: Hello world!
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
class HelloWorldApp extends Component {
render() {
return (
<Text>Hello world!</Text>
);
}
}
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
GoalKicker.com – React Native Notes for Professionals
12
Chapter 3: Props
Props, or properties, are data that is passed to child components in a React application. React components render
UI elements based on their props and their internal state. The props that a component takes (and uses) defines
how it can be controlled from the outside.
Section 3.1: PropTypes
The prop-types package allows you to add runtime type checking to your component that ensures the types of the
props passed to the component are correct. For instance, if you don't pass a name or isYummy prop to the
component below it will throw an error in development mode. In production mode the prop type checks are not
done. Defining propTypes can make your component more readable and maintainable.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AppRegistry, Text, View } from 'react-native';
import styles from './styles.js';
class Recipe extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
isYummy: PropTypes.bool.isRequired
}
render() {
return (
<View style={styles.container}>
<Text>{this.props.name}</Text>
{this.props.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
</View>
)
}
}
AppRegistry.registerComponent('Recipe', () => Recipe);
// Using the component
<Recipe name="Pancakes" isYummy={true} />
Multiple PropTypes
You can also have multiple propTypes for one props. For example, the name props I'm taking can also be an object,
I can write it as.
static propTypes = {
name: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
])
}
Children Props
There is also a special props called children, which is not passed in like
GoalKicker.com – React Native Notes for Professionals
13
<Recipe children={something}/>
Instead, you should do this
<Recipe>
<Text>Hello React Native</Text>
</Recipe>
then you can do this in Recipe's render:
return (
<View style={styles.container}>
{this.props.children}
{this.props.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
</View>
)
You will have a <Text> component in your Recipe saying Hello React Native, pretty cool hum?
And the propType of children is
Publicité
children: PropTypes.node
Section 3.2: What are props?
Props are used to transfer data from parent to child component. Props are read only. Child component can only get
the props passed from parent using this.props.keyName. Using props one can make his component reusable.
Section 3.3: Use of props
Once setup is completed. Copy the code below to index.android.js or to index.ios.js file to use the props.
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
class Greeting extends Component {
render() {
return (
<Text>Hello {this.props.name}!</Text>
);
}
}
class LotsOfGreetings extends Component {
render() {
return (
<View style={{alignItems: 'center'}}>
<Greeting name='Rexxar' />
<Greeting name='Jaina' />
<Greeting name='Valeera' />
</View>
);
}
}
AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);
GoalKicker.com – React Native Notes for Professionals
14
Using props one can make his component generic. For example, you have a Button component. You can pass
different props to that component, so that one can place that button anywhere in his view.
source: Props-React Native
Section 3.4: Default Props
defaultProps allows you to set default prop values for your component. In the below example if you do not pass the
name props, it will display John otherwise it will display the passed value
class Example extends Component {
render() {
return (
<View>
<Text>{this.props.name}</Text>
</View>
)
}
}
Example.defaultProps = {
name: 'John'
}
GoalKicker.com – React Native Notes for Professionals
15
Chapter 4: Multiple props rendering
Section 4.1: render multiple variables
For rendering multiple props or variables we can use ``.
render() {
let firstName = 'test';
let lastName = 'name';
return (
<View style={styles.container}>
<Text>{${firstName} ${lastName} } </Text>
</View>
);
}
Output: test name
GoalKicker.com – React Native Notes for Professionals
16
Chapter 5: Modal
Prop
details
animationType
it's an enum of ('none', 'slide', 'fade') and it controls modal animation.
visible
onShow
its a bool that controls modal visiblity.
it allows passing a function that will be called once the modal has been shown.
transparent
bool to set transparency.
onRequestClose (android)
it always defining a method that will be called when user tabs back button
onOrientationChange (IOS)
it always defining a method that will be called when orientation changes
supportedOrientations (IOS) enum('portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right')
Modal component is a simple way to present content above an enclosing view.
Section 5.1: Modal Basic Example
import React, { Component } from 'react';
import {
Modal,
Text,
View,
Button,
StyleSheet,
} from 'react-native';
const styles = StyleSheet.create({
mainContainer: {
marginTop: 22,
},
modalContainer: {
marginTop: 22,
},
});
class Example extends Component {
constructor() {
super();
this.state = {
visibility: false,
};
}
setModalVisibility(visible) {
this.setState({
visibility: visible,
});
}
render() {
return (
<View style={styles.mainContainer}>
<Modal
animationType={'slide'}
transparent={false}
visible={this.state.visibility}
>
<View style={styles.modalContainer}>
<View>
GoalKicker.com – React Native Notes for Professionals
17
<Text>I'm a simple Modal</Text>
<Button
color="#000"
onPress={() => this.setModalVisibility(!this.state.visibility)}
title="Hide Modal"
/>
</View>
</View>
</Modal>
<Button
color="#000"
onPress={() => this.setModalVisibility(true)}
title="Show Modal"
/>
</View>
);
}
}
export default Example;
Section 5.2: Transparent Modal Example
See this example here.
import React, { Component } from 'react';
import { Text, View, StyleSheet, Button, Modal } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
state = {
modalVisible: false,
};
_ha...