React Native
React Native
#react-
native
Table of Contents
About 1
Remarks 2
Examples 2
Start the terminal and run the following commands to install nodeJS: 2
Obs: Always check if the version on android/app/build.gradle is the same as the Build Tool 4
Open Android AVD to set up a virtual android. Execute the command line: 5
Examples 18
Hardware back button handling using BackHandler and Navigation Properties (without using d 19
Examples 21
Animate an Image 21
Examples 22
Chapter 5: Components 24
Examples 24
Basic Component 24
Stateful Component 24
Stateless Component 24
Introduction 26
Remarks 26
Examples 26
Examples 28
Android 29
iOS 29
Chapter 8: Debugging 32
Syntax 32
Examples 32
Using console.log() 32
Introduction 33
Examples 33
How to start 33
Examples 34
Hello world! 34
Syntax 35
Remarks 35
Examples 35
WebSockets 36
Examples 40
Image Module 40
Image Example 40
To fit an Image 40
Introduction 42
Examples 42
Examples 45
Flexbox 45
flexDirection 45
Alignment axis 46
Alignment 48
Flex size 48
Introduction 49
Examples 49
Outgoing Links 49
URI Schemes 49
Incomming Links 50
Examples 51
Simple Example 51
Introduction 52
Parameters 52
Examples 52
Examples 55
Examples 56
Introduction 56
Example 56
Examples 58
Navigator 58
Introduction 63
Examples 67
Introduction 68
Examples 68
Use of props 68
PropTypes 69
Default Props 70
Introduction 71
Remarks 71
Examples 71
Remarks 76
Examples 76
Refresh Control 76
Introduction 79
Examples 79
Functions in JSX 79
Introduction 81
Examples 81
Navigator component 81
Remarks 82
Examples 82
Syntax 83
Examples 83
setState 83
Full Example 83
Initialize State 85
Introduction 86
Syntax 86
Remarks 86
Examples 86
Conditional Styling 87
Introduction 89
Examples 89
Introduction 91
Examples 91
Credits 92
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: react-native
It is an unofficial and free react-native ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official react-native.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
http://www.riptutorial.com/ 1
Chapter 1: Getting started with react-native
Remarks
React Native lets you build mobile apps using only JavaScript. It uses the same design as React,
letting you compose a rich mobile UI from declarative components.
With React Native, you don't build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You
build a real mobile app that's indistinguishable from an app built using Objective-C or Java. React
Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just
put those building blocks together using JavaScript and React.
• Website
• Documentation
• GitHub Repository
Examples
Setup for Linux (Ubuntu)
1) Setup Node.JS
http://www.riptutorial.com/ 2
or
node -v
2) Setup Java
http://developer.android.com/sdk/index.html
export ANDROID_HOME=/YOUR/LOCAL/ANDROID/SDK
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
4) Setup emulator:
android
Select "SDK Platforms" from within the SDK Manager and you should see a blue checkmark next
to "Android 7.0 (Nougat)". In case it is not, click on the checkbox and then "Apply".
http://www.riptutorial.com/ 3
5) Start a project
android {
compileSdkVersion XX
buildToolsVersion "XX.X.X"
...
http://www.riptutorial.com/ 4
Open Android AVD to set up a virtual android. Execute the
command line:
android avd
react-native run-android
react-native start
https://developer.apple.com/download/
• Git git
*If you have installed XCode, Git is already installed, otherwise run the following
• Latest JDK
• Android Studio
http://www.riptutorial.com/ 5
http://www.riptutorial.com/ 6
Choose both Performance and Android Virtual Device
http://www.riptutorial.com/ 7
http://www.riptutorial.com/ 8
After installation, choose Configure -> SDK Manager from the Android Studio welcome
window.
http://www.riptutorial.com/ 9
http://www.riptutorial.com/ 10
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.
http://www.riptutorial.com/ 11
http://www.riptutorial.com/ 12
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.
http://www.riptutorial.com/ 13
http://www.riptutorial.com/ 14
• 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
You will need Xcode for iOS and Android Studio for android, node.js, the React Native command
line tools, and Watchman.
Node comes with npm, which lets you install the React Native command line interface.
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.
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.
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.
http://www.riptutorial.com/ 15
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.
• 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.
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)
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
A Step by Step guide with images can be found here for this section.
[Right click] "Start" menu -> System -> Advanced System Settings -> Environment Variables
http://www.riptutorial.com/ 16
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:
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.
http://www.riptutorial.com/ 17
Chapter 2: Android - Hardware Back Button
Examples
Detect Hardware back button presses in Android
BackAndroid.addEventListener('hardwareBackPress', function() {
if (!this.onMainScreen()) {
this.goBack();
return true;
}
return false;
});
Note: this.onMainScreen() and this.goBack() are not built in functions, you also need to implement
those. (https://github.com/immidi/react-
native/commit/ed7e0fb31d842c63e8b8dc77ce795fac86e0f712)
This is an example on how to use React Native's BackAndroid along with the Navigator.
componentWillMount registers an event listener to handle the taps on the back button. It checks if
there is another view in the history stack, and if there is one, it goes back -otherwise it keeps the
default behaviour.
import {
BackAndroid,
Navigator,
} from 'react-native';
constructor(props) {
super(props);
this.navigator;
}
componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', () => {
if (this.navigator && this.navigator.getCurrentRoutes().length > 1) {
this.navigator.pop();
return true;
}
http://www.riptutorial.com/ 18
return false;
});
}
renderScene(route, navigator) {
this.navigator = navigator;
return (
<SceneContainer
title={route.title}
route={route}
navigator={navigator}
onBack={() => {
if (route.index > 0) {
navigator.pop();
}
}}
{...this.props} />
);
}
render() {
return (
<Navigator
initialRoute={<View />}
renderScene={this.renderScene.bind(this)}
navigationBar={
<Navigator.NavigationBar
style={{backgroundColor: 'gray'}}
routeMapper={RouteMapper} />
} />
);
}
};
This example will show you back navigation which is expected generally in most of the flows. You
will have to add following code to every screen depending on expected behavior. There are 2
cases:
1. If there are more than 1 screen on stack, device back button will show previous screen.
2. If there is only 1 screen on stack, device back button will exit app.
constructor(props) {
super(props)
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
http://www.riptutorial.com/ 19
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
this.props.navigation.goBack(null);
return true;
}
In this case, no need to handle anything on that screen where you want to exit app.
{...}
ComponentWillMount(){
BackHandler.addEventListener('hardwareBackPress',()=>{
if (!this.onMainScreen()) {
this.goBack();
return true;
}
return false;
});
}
http://www.riptutorial.com/ 20
Chapter 3: Animation API
Examples
Animate an Image
http://www.riptutorial.com/ 21
Chapter 4: Command Line Instructions
Examples
Check version installed
$ react-native -v
Example Output
react-native-cli: 0.2.0
react-native: n/a - not inside a React Native project directory //Output from different
folder
react-native: react-native: 0.30.0 // Output from the react native project directory
In the app folder find package.json and modify the following line to include the latest version, save
the file and close.
"react-native": "0.32.0"
In terminal:
$ npm install
Followed by
$ react-native upgrade
Logging
Android
$ react-native log-android
iOS
$ react-native log-ios
$ react-native start
http://www.riptutorial.com/ 22
On latest version of React Native, no need to run the packager. It will run automatically.
By default this starts the server at port 8081. To specify which port the server is on
To initialize
cd MyAwesomeProject
react-native run-android
cd MyAwesomeProject
react-native run-ios
If you either have apps generated with pre-android support or just did that on purpose, you can
always add android project to your app.
$ react-native android
This will generate android folder and index.android.js inside your app.
http://www.riptutorial.com/ 23
Chapter 5: Components
Examples
Basic Component
Stateful Component
Stateless Component
As the name implies, Stateless Components do not have any local state. They are also known as
Dumb Components. Without any local state, these components do not need lifecycle methods or
much of the boilerplate that comes with a stateful component.
http://www.riptutorial.com/ 24
Class syntax is not required, you can simply do const name = ({props}) => ( ... ). Generally
stateless components are more concise as a result.
Beneath is an example of two stateless components App and Title, with a demonstration of
passing props between components:
This is the recommended pattern for components, when possible. As in the future optimisations
can be made for these components, reducing memory allocations and unnecessary checks.
http://www.riptutorial.com/ 25
Chapter 6: Create a shareable APK for
android
Introduction
Steps to create an APK (signed and unsigned) which you can install on a device using CLI and
share as well:
Problem statement: I've built my app, I can run it on my local emulator (and also on my android
device by changing debug server). But, I want to build an apk that I can send to someone without
access to development server and I want them to be able to test application.
Remarks
A more detailed description is also mentioned here: https://facebook.github.io/react-
native/docs/signed-apk-android.html
Examples
Create a key to sign the APK
keytool -genkey -v -keystore my-app-key.keystore -alias my-app-alias -keyalg RSA -keysize 2048
-validity 10000
Upload the APK to your phone. The -r flag will replace the existing app (if it exists)
http://www.riptutorial.com/ 26
./app/build/outputs/apk/app-release.apk
http://www.riptutorial.com/ 27
Chapter 7: Custom Fonts
Examples
Steps to use custom fonts in React Native (Android)
• Create a folder in your project folder, and add your fonts to it. Example:
○ Example: Here we added a folder in root called "mystuff", then "fonts", and inside it we
placed our fonts:
○
{
...
"rnpm": {
"assets": [
"path/to/fontfolder"
]
},
...
}
○ For the example above, our package.json would now have a path of "mystuff/fonts":
"rnpm": {
"assets": [
"mystuff/fonts"
]
}
http://www.riptutorial.com/ 28
• Run react-native link command.
Android
FONT-NAME is the words before the extension in file. Example: Your font's file name is
Roboto-Regular.ttf, so you would set fontFamily: Roboto-Regular.
iOS
FONT-NAME is "Full Name" found after right clicking, on the font file, then clicking on "Get
Info". ( Source: https://stackoverflow.com/a/16788493/2529614 ), in the screenshot below,
the file name is MM Proxima Nova Ultra bold.otf, however "Full Name" is "Proxima Nova
Semibold", thus you would set fontFamily: Proxima Nova Semibold. Screenshot -
• Run react-native run-ios or react-native run-android again (this will recompile with the
resources)
http://www.riptutorial.com/ 29
Steps to use custom fonts in React Native (iOS)
2. Make sure that they are included in the Target Membership column
Click on the font from the navigator, and check if the font included.
click on your Xcode project file, select "Build Phases, select "Copy Bundle Resources". Check if
your font is added.
http://www.riptutorial.com/ 30
from the application main folder open Info.plist, click on "Information Property List", and then click
the plus sign (+). from drop down list choose "Fonts provided by application".
expand Fonts Provided by Application and add the Font Name exactly to value column
<Text style={{fontFamily:'IndieFlower'}}>
Welcome to React Native!
</Text>
http://www.riptutorial.com/ 31
Chapter 8: Debugging
Syntax
• debugger;
Examples
Start Remote JS Debugging in Android
You can start the remote debugging from Developer menu. After selecting the enable remote
debugging it will open Google Chrome, So that you can log the output into your console. You can
also write debugger syntax into your js code.
Using console.log()
You can print log message in the terminal using console.log(). To do so, open a new terminal and
run following command for Android:
react-native log-android
react-native log-ios
You will now start to see all the log message in this terminal
http://www.riptutorial.com/ 32
Chapter 9: ESLint in react-native
Introduction
This is the topic for ESLint rules explanation for react-native.
Examples
How to start
It's highly recommended to use ESLint in your project on react-native. ESLint is a tool for code
validation using specific rules provided by community.
For react-native you can use rulesets for javascript, react and react-native.
Common ESLint rules with motivation and explanations for javascript you can find here:
https://github.com/eslint/eslint/tree/master/docs/rules . You can simply add ready ruleset from
ESLint developers by adding in your .eslintr.json to 'extends' node 'eslint:recommended'. (
"extends": ["eslint:recommended"] ) More about ESLint configuring you can read here:
http://eslint.org/docs/developer-guide/development-environment . It's recommended to read full
doc about this extremely useful tool.
Next, full docs about rules for ES Lint react plugin you can find here:
https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules . Important note: not all
rules from react are relative to react-native. For example: react/display-name and react/no-
unknown-property for example. Another rules are 'must have' for every project on react-native,
such as react/jsx-no-bind and react/jsx-key.
For correct working of this tool in react-native env you might need to set value or 'env' in your
config to this: "env": { "browser": true, "es6": true, "amd": true },
http://www.riptutorial.com/ 33
Chapter 10: Hello World
Examples
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.
Hello world!
http://www.riptutorial.com/ 34
Chapter 11: HTTP Requests
Syntax
• fetch(url, options)[.then(...)[.catch(...)]]
Remarks
• The Fetch API is the most commonly used API for HTTP requests. It is modern, flexible and
it uses promises.
• The XMLHttpRequest API is also used for HTTP requests and is mainly included so that
developers may use their favorite existing libraries, like ApiSauce.
• The Websocket API may be used for "live" data in real time scenarios, such as in chat
applications.
Examples
Using Promises with the fetch API and Redux
Redux is the most common state management library used with React-Native. The following
example demonstrates how to use the fetch API and dispatch changes to your applications state
reducer using redux-thunk.
http://www.riptutorial.com/ 35
type: 'ERROR_RECIPE',
message: err.reason,
status: err.status
});
});
}
})
.catch((err) => {
// Runs if there is a general JavaScript error.
dispatch(error('There was a problem with the request.'));
});
};
};
WebSockets
ws.onopen = () => {
// connection opened
It should be noted that Fetch does not support progress callbacks. See:
https://github.com/github/fetch/issues/89.
fetch('/login', {
method: 'POST',
body: form,
mode: 'cors',
cache: 'default',
}).then(session => onLogin(session), failure => console.error(failure));
http://www.riptutorial.com/ 36
More details about fetch can be found at MDN
request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();
Install socket.io-client
Import module
constructor(props){
super(props);
this.socket = SocketIOClient('http://server:3000');
}
Now in order to use your socket connection properly, you should bind your functions in constructor
too. Let's assume that we have to build a simple application, which will send a ping to a server via
socket after every 5 seconds (consider this as ping), and then the application will get a reply from
the server. To do so, let's first create these two functions:
_sendPing(){
//emit a dong message to socket server
socket.emit('ding');
}
_getReply(data){
//get reply from socket server, log it to console
console.log('Reply from server:' + data);
}
http://www.riptutorial.com/ 37
Now, we need to bind these two functions in our constructor:
constructor(props){
super(props);
this.socket = SocketIOClient('http://server:3000');
After that, we also need to link _getReply function with the socket in order to receive the message
from the socket server. To do this we need to attach our _getReply function with socket object.
Add the following line to our constructor:
this.socket.on('dong', this._getReply);
Now, whenever socket server emits with the 'dong' your application will able to receive it.
Configure
It's easy to configure. For this purpose you can create file axios.js for example:
Requests
To avoid using pattern 'Swiss knife' for every service on your backend you can create separate file
with methods for this within folder for integration functionality:
const UserService = {
getCallToAction() {
return axios.get('api/user/dosomething').then(response => response.data)
.catch(errorHandling);
http://www.riptutorial.com/ 38
},
}
export default UserService;
Testing
With this lib you can set to axios any responce you want for testing it. Also you can configure
some special errors for your axois'es methods. You can add it to your axios.js file created in
prevous step:
for example.
Redux Store
Sometimes you need to add to headers authorize token, that you probably store in your redux
store.
In this case you'll need another file, interceptors.js with this function:
axios.interceptors.request.use(getAuthToken(this.state.store));
and then all your requests will be followed with your authorization token.
As you can see axios is very simple, configurable and useful library for applications based on
react-native.
http://www.riptutorial.com/ 39
Chapter 12: Images
Examples
Image Module
You're going to have to import Image from the react-native package like so then use it:
You can also use a local image with a slightly different syntax but same logic like so:
Note:- You should give height, width to the image otherwise it won't show.
Image Example
To fit an Image
<Image
resizeMode="contain"
style={{height: 100, width: 100}}
source={require('../assets/image.png')} />
<Image style={[this.props.imageStyle]}
source={this.props.imagePath
? this.props.imagePath
: require('../theme/images/resource.png')}
http://www.riptutorial.com/ 40
/>
If the path is available in imagePath then it will be assigned to source else the default image path
will be assigned.
http://www.riptutorial.com/ 41
Chapter 13: Integration with Firebase for
Authentication
Introduction
//Replace firebase values with your app api values import firebase from 'firebase';
Examples
React Native - ListView with Firebase
This is what I do when I'm working with Firebase and I want to use ListView.
Posts.js
componentWillMount() {
firebase.database().ref('Posts/').on('value', function(data) {
this.setState({ posts: data.val() });
});
}
render() {
return <PostsList posts={this.state.posts}/>
}
}
PostsList.js
http://www.riptutorial.com/ 42
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
}),
}
}
componentDidMount() {
this.setState({dataSource: this.getDataSource(this.props.posts)});
}
componentWillReceiveProps(props) {
this.setState({dataSource: this.getDataSource(props.posts)});
}
render() {
return(
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
enableEmptySections={true}
/>
);
}
}
I want to point out that in Posts.js, I'm not importing firebase because you only need to import it
once, in the main component of your project (where you have the navigator) and use it anywhere.
This is the solution someone suggested in a question I asked when I was struggling with
ListView. I thought it would be nice to share it.
Source: [http://stackoverflow.com/questions/38414289/react-native-listview-not-rendering-data-
from-firebase][1]
http://www.riptutorial.com/ 43
databaseURL: "yourDomainBaseURL",
projectId: "yourProjectID",
storageBucket: "storageBUcketValue",
messagingSenderId: "senderIdValue"
});
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess)
.catch(this.onLoginFail)
})
}
http://www.riptutorial.com/ 44
Chapter 14: Layout
Examples
Flexbox
Flexbox is a layout mode providing for the arrangement of elements on a page such that the
elements behave predictably when the page layout must accommodate different screen sizes and
different display devices. By default flexbox arranges children in a column. But you can change it
to row using flexDirection: 'row'.
flexDirection
http://www.riptutorial.com/ 45
Alignment axis
http://www.riptutorial.com/ 46
});
http://www.riptutorial.com/ 47
http://www.riptutorial.com/ 48
Chapter 15: Linking Native API
Introduction
Linking API enables you to both send and receive links between applications. For example,
opening the Phone app with number dialed in or opening the Google Maps and starting a
navigation to a chosen destination. You can also utilise Linking to make your app able to respond
to links opening it from other applications.
Examples
Outgoing Links
Linking.openURL(url)
.catch(err => console.error('An error occurred ', err))
The preferred method is to check if any installed app can handle a given URL beforehand.
Linking.canOpenURL(url)
.then(supported => {
if (!supported) {
console.log('Unsupported URL: ' + url)
} else {
return Linking.openURL(url)
}
}).catch(err => console.error('An error occurred ', err))
URI Schemes
Target App Example Reference
http://www.riptutorial.com/ 49
Target App Example Reference
[1] Opens the calendar at the stated number of seconds since 1. 1. 2001 (UTC?). For some
reason this API is undocumented by Apple.
Incomming Links
You can detect when your app is launched from an external URL.
componentDidMount() {
const url = Linking.getInitialURL()
.then((url) => {
if (url) {
console.log('Initial url is: ' + url)
}
}).catch(err => console.error('An error occurred ', err))
}
http://www.riptutorial.com/ 50
Chapter 16: ListView
Examples
Simple Example
ListView - A core component designed for efficient display of vertically scrolling lists of changing
data. The minimal API is to create a ListView.DataSource, populate it with a simple array of data
blobs, and instantiate a ListView component with that data source and a renderRow callback
which takes a blob from the data array and returns a renderable component.
Minimal example:
getInitialState: function() {
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
return {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
};
},
render: function() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
);
},
ListView also supports more advanced features, including sections with sticky section headers,
header and footer support, callbacks on reaching the end of the available data (onEndReached)
and on the set of rows that are visible in the device viewport change (onChangeVisibleRows), and
several performance optimizations.
There are a few performance operations designed to make ListView scroll smoothly while
dynamically loading potentially very large (or conceptually infinite) data sets:
• Only re-render changed rows - the rowHasChanged function provided to the data source
tells the ListView if it needs to re-render a row because the source data has changed - see
ListViewDataSource for more details.
• Rate-limited row rendering - By default, only one row is rendered per event-loop
(customizable with the pageSize prop). This breaks up the work into smaller chunks to
reduce the chance of dropping frames while rendering rows.
http://www.riptutorial.com/ 51
Chapter 17: Modal
Introduction
Modal component is a simple way to present content above an enclosing view.
Parameters
Prop details
onRequestClose (android it always defining a method that will be called when user tabs
) back button
Examples
Modal Basic Example
http://www.riptutorial.com/ 52
marginTop: 22,
},
});
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>
<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>
);
}
}
http://www.riptutorial.com/ 53
export default class App extends Component {
state = {
modalVisible: false,
};
_handleButtonPress = () => {
this.setModalVisible(true);
};
render() {
var modalBackgroundStyle = {
backgroundColor: 'rgba(0, 0, 0, 0.5)'
};
var innerContainerTransparentStyle = {backgroundColor: '#fff', padding: 20};
return (
<View style={styles.container}>
<Modal
animationType='fade'
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => this.setModalVisible(false)}
>
<View style={[styles.container, modalBackgroundStyle]}>
<View style={innerContainerTransparentStyle}>
<Text>This is a modal</Text>
<Button title='close'
onPress={this.setModalVisible.bind(this, false)}/>
</View>
</View>
</Modal>
<Button
title="Press me"
onPress={this._handleButtonPress}
/>
</View>
);
}
}
http://www.riptutorial.com/ 54
Chapter 18: Multiple props rendering
Examples
render multiple variables
render() {
let firstName = 'test';
let lastName = 'name';
return (
<View style={styles.container}>
<Text>{`${firstName} ${lastName}` } </Text>
</View>
);
}
http://www.riptutorial.com/ 55
Chapter 19: Native Modules
Examples
Create your Native Module (IOS)
Introduction
from http://facebook.github.io/react-native/docs/native-modules-ios.html
Sometimes an app needs access to platform API, and React Native doesn't have a
corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift
or C++ code without having to reimplement it in JavaScript, or write some high
performance, multi-threaded code such as for image processing, a database, or any
number of advanced extensions.
A Native Module is simply an Objective-C Class that implements the RCTBridgeModule protocol.
Example
In your Xcode project create a new file and select Cocoa Touch Class, in the creation wizard
choose a name for your Class (e.g. NativeModule), make it a Subclass of: NSObject and choose
Objective-C for the language.
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
@end
#import "NativeModuleEx.h"
@implementation NativeModuleEx
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(testModule:(NSString *)string )
{
http://www.riptutorial.com/ 56
NSLog(@"The string '%@' comes from JavaScript! ", string);
}
@end
RCT_EXPORT_MODULE()will make your module accessible in JavaScript, you can pass it an optional
argument to specify its name. If no name is provided it will match the Objective-C class name.
RCT_EXPORT_METHOD()will expose your method to JavaScript, only the methods you export using this
macro will be accessible in JavaScript.
http://www.riptutorial.com/ 57
Chapter 20: Navigator Best Practices
Examples
Navigator
Navigator is React Native's default navigator. A Navigator component manages a stack of route
objects, and provides methods for managing that stack.
<Navigator
ref={(navigator) => { this.navigator = navigator }}
initialRoute={{ id: 'route1', title: 'Route 1' }}
renderScene={this.renderScene.bind(this)}
configureScene={(route) => Navigator.SceneConfigs.FloatFromRight}
style={{ flex: 1 }}
navigationBar={
// see "Managing the Navigation Bar" below
<Navigator.NavigationBar routeMapper={this.routeMapper} />
}
/>
First of all, notice the initialRoute prop. A route is simply a javascript object, and can take
whatever shape you want, and have whatever values you want. It's the primary way you'll pass
values and methods between components in your navigation stack.
The Navigator knows what to render based on the value returned from its renderScene prop.
renderScene(route, navigator) {
if (route.id === 'route1') {
return <ExampleScene navigator={navigator} title={route.title} />; // see below
} else if (route.id === 'route2') {
return <ExampleScene navigator={navigator} title={route.title} />; // see below
}
}
function ExampleScene(props) {
function forward() {
// this route object will passed along to our `renderScene` function we defined above.
props.navigator.push({ id: 'route2', title: 'Route 2' });
}
function back() {
// `pop` simply pops one route object off the `Navigator`'s stack
props.navigator.pop();
}
return (
http://www.riptutorial.com/ 58
<View>
<Text>{props.title}</Text>
<TouchableOpacity onPress={forward}>
<Text>Go forward!</Text>
</TouchableOpacity>
<TouchableOpacity onPress={back}>
<Text>Go Back!</Text>
</TouchableOpacity>
</View>
);
}
You can configure the Navigator's transitions with the configureScene prop. This is a function that's
passed the route object, and needs to return a configuration object. These are the available
configuration objects:
• Navigator.SceneConfigs.PushFromRight (default)
• Navigator.SceneConfigs.FloatFromRight
• Navigator.SceneConfigs.FloatFromLeft
• Navigator.SceneConfigs.FloatFromBottom
• Navigator.SceneConfigs.FloatFromBottomAndroid
• Navigator.SceneConfigs.FadeAndroid
• Navigator.SceneConfigs.HorizontalSwipeJump
• Navigator.SceneConfigs.HorizontalSwipeJumpFromRight
• Navigator.SceneConfigs.VerticalUpSwipeJump
• Navigator.SceneConfigs.VerticalDownSwipeJump
You can return one of these objects without modification, or you can modify the configuration
object to customize the navigation transitions. For example, to modify the edge hit width to more
closely emulate the iOS UINavigationController's interactivePopGestureRecognizer:
configureScene={(route) => {
return {
...Navigator.SceneConfigs.FloatFromRight,
gestures: {
pop: {
...Navigator.SceneConfigs.FloatFromRight.gestures.pop,
edgeHitWidth: Dimensions.get('window').width / 2,
},
},
};
}}
The Navigator component comes with a navigationBar prop, which can theoretically take any
properly configured React component. But the most common implementation uses the default
Navigator.NavigationBar. This takes a routeMapper prop that you can use to configure the
appearance of the navigation bar based on the route.
http://www.riptutorial.com/ 59
A routeMapper is a regular javascript object with three functions: Title, RightButton, and LeftButton.
For example:
const routeMapper = {
return (
<TouchableOpacity
onPress={() => navigator.pop()}
style={styles.navBarLeftButton}
>
<Text>Back</Text>
</TouchableOpacity>
);
},
See more
For more detailed documentation of each prop, see the the official React Native Documentation for
Navigator, and the React Native guide on Using Navigators.
key A unique string that can be used to refer to the particular scene.
http://www.riptutorial.com/ 60
title make a NavBar and give it a title 'Home'
Example:
Import this file in the main App.js(index file) and render it. For more information can visit this link.
With the help of react-navigation, you can add navigation to your app really easy.
Install react-navigation
Example:
return (
<Button
title='Go to Second Page'
onPress={() =>
navigate('SecondPage', { name: 'Awesomepankaj' })
}
/>
http://www.riptutorial.com/ 61
);
}
}
render() {
const { goBack } = this.props.navigation;
return (
<View>
<Text>Welcome to Second Page</Text>
<Button
title="Go back to First Page"
onPress={() => goBack()}
/>
</View>
);
}
}
http://www.riptutorial.com/ 62
Chapter 21: Navigator with buttons injected
from pages
Examples
Introduction
Instead of bloating your main js file that contains your navigator with buttons. It's cleaner to just
inject buttons on-demand in any page that you need.
//In the page "Home", I want to have the right nav button to show
//a settings modal that resides in "Home" component.
componentWillMount() {
this.props.route.navbarTitle = "Home";
this.props.route.rightNavButton = {
text: "Settings",
onPress: this._ShowSettingsModal.bind(this)
};
}
'use strict';
const {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
Alert,
TouchableHighlight
} = ReactNative;
renderScene(route, navigator) {
switch(route.name) {
case "Home":
//You must pass route as a prop for this trick to work properly
return <Home route={route} navigator={navigator} {...route.passProps} />
default:
return (
<Text route={route}
style={styles.container}>
http://www.riptutorial.com/ 63
Your route name is probably incorrect {JSON.stringify(route)}
</Text>
);
}
}
render() {
return (
<Navigator
navigationBar={
<Navigator.NavigationBar
style={ styles.navbar }
routeMapper={ NavigationBarRouteMapper } />
}
/>
);
}
}
http://www.riptutorial.com/ 64
},
Title(route, navigator, index, navState) {
//You can inject the title aswell. If you don't we'll use the route name.
return (<Text style={styles.navbarTitle}>{route.navbarTitle || route.name}</Text>);
}
};
//This trick depends on that componentWillMount fires before the navbar is created
componentWillMount() {
this.props.route.navbarTitle = "Home";
this.props.route.rightNavButton = {
text: "Button",
onPress: this._doSomething.bind(this)
};
}
render() {
return (
<View style={styles.container}>
<Text>You are home</Text>
</View>
);
}
}
http://www.riptutorial.com/ 65
paddingRight: 8,
},
navbarButtonText: {
fontSize: 17,
color: "#007AFF"
}
});
http://www.riptutorial.com/ 66
Chapter 22: Platform Module
Examples
Find the OS Type/Version
The first step is to import Platform from the 'react-native' package like so:
After you've done that, you can go ahead and access the OS type through Platform.OS allowing
you to use it in conditional statements like
If you want to detect the Android version, you can use Platform.Version like so:
For iOS, Platform.Version is returning a String, for complex condition don't forget to parse it.
If the platform specific logic is complex, one can render two different files based on platform. Ex:
• MyTask.android.js
• MyTask.ios.js
http://www.riptutorial.com/ 67
Chapter 23: Props
Introduction
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.
Examples
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.
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.
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.
http://www.riptutorial.com/ 68
source: Props-React Native
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.
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
<Recipe children={something}/>
http://www.riptutorial.com/ 69
Instead, you should do this
<Recipe>
<Text>Hello React Native</Text>
</Recipe>
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?
children: PropTypes.node
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
Example.defaultProps = {
name: 'John'
}
http://www.riptutorial.com/ 70
Chapter 24: PushNotification
Introduction
We can add Push Notification to react native app by using the npm module react-native-push-
notification by zo0r. This enables for a cross platform development.
Installation
react-native link
Remarks
Refer GitHub Repo of this module for more details.
Examples
Push Notification Simple Setup
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
constructor(props){
super(props);
this.NewNotification = this.NewNotification.bind(this);
}
componentDidMount(){
PushNotification.configure({
http://www.riptutorial.com/ 71
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
},
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or
not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true,
});
NewNotification(){
PushNotification.localNotificationSchedule({
message: "My Notification Message", // (required)
date: date,// (optional) for setting delay
largeIcon:""// set this blank for removing large icon
//smallIcon: "ic_notification", // (optional) default: "ic_notification" with
fallback for "ic_launcher"
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Push Notification
</Text>
<View style={styles.Button} >
<Button
onPress={()=>{this.NewNotification()}}
title="Show Notification"
style={styles.Button}
color="#841584"
accessibilityLabel="Show Notification"
/>
</View>
</View>
);
}
}
http://www.riptutorial.com/ 72
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
Button:{
margin: 10,
}
});
Here's a simple example to demonstrate that how can we jump/open a specific screen based on
the notification. For example, when a user clicks on the notification, the app should open and
directly jump to notifications page instead of home page.
'use strict';
this.handleNotification = this.handleNotification.bind(this);
}
handleNotification(notification)
{
console.log('handleNotification');
var notificationId = ''
//your logic to get relevant information from the notification
//here you navigate to a scene in your app based on the notification info
this.navigator.push({ id: Constants.ITEM_VIEW_ID, item: item });
http://www.riptutorial.com/ 73
}
componentDidMount()
{
var that = this;
PushNotification.configure({
that.handleNotification(notification);
},
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or
not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true,
});
}
render()
{
return (
<Navigator
ref={(nav) => this.navigator = nav }
initialRoute={initialRoute}
renderScene={this.renderScene.bind(this)}
configureScene={(route) =>
{
if (route.sceneConfig)
{
return route.sceneConfig;
}
return Navigator.SceneConfigs.FadeAndroid;
}
http://www.riptutorial.com/ 74
}
/>
);
}
renderScene(route, navigator)
{
switch (route.id)
{
// do your routing here
case 'mainview':
return ( <MainView navigator={navigator} /> );
default:
return ( <MainView navigator={navigator} /> );
}
}
}
http://www.riptutorial.com/ 75
Chapter 25: RefreshControl with ListView
Remarks
References:
RefreshControl: https://facebook.github.io/react-native/docs/refreshcontrol.html
ListView: https://facebook.github.io/react-native/docs/listview.html
Examples
Refresh Control
_refreshControl(){
return (
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={()=>this._refreshListView()} />
)
}
_refreshListView(){
//Start Rendering Spinner
this.setState({refreshing:true})
this.state.cars.push(
{name:'Fusion',color:'Black'},
{name:'Yaris',color:'Blue'}
)
//Updating the dataSource with new data
this.setState({ dataSource:
this.state.dataSource.cloneWithRows(this.state.cars) })
this.setState({refreshing:false}) //Stop Rendering Spinner
}
here we are updating the array and after that we will update the dataSource. we can use fetch to
request something from server and use async/await.
RefreshControl is used inside a ScrollView or ListView to add pull to refresh functionality. at this
example we will use it with ListView
http://www.riptutorial.com/ 76
'use strict'
import React, { Component } from 'react';
import { StyleSheet, View, ListView, RefreshControl, Text } from 'react-native'
componentWillMount(){
this.setState({ dataSource:
this.state.dataSource.cloneWithRows(this.state.cars) })
}
render() {
return (
<View style={{flex:1}}>
<ListView
refreshControl={this._refreshControl()}
dataSource={this.state.dataSource}
renderRow={(car) => this._renderListView(car)}>
</ListView>
</View>
)
}
_renderListView(car){
return(
<View style={styles.listView}>
<Text>{car.name}</Text>
<Text>{car.color}</Text>
</View>
)
}
_refreshControl(){
return (
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={()=>this._refreshListView()} />
)
}
_refreshListView(){
//Start Rendering Spinner
this.setState({refreshing:true})
this.state.cars.push(
{name:'Fusion',color:'Black'},
{name:'Yaris',color:'Blue'}
)
//Updating the dataSource with new data
http://www.riptutorial.com/ 77
this.setState({ dataSource:
this.state.dataSource.cloneWithRows(this.state.cars) })
this.setState({refreshing:false}) //Stop Rendering Spinner
}
listView: {
flex: 1,
backgroundColor:'#fff',
marginTop:10,
marginRight:10,
marginLeft:10,
padding:10,
borderWidth:.5,
borderColor:'#dddddd',
height:70
}
})
module.exports = RefreshControlExample
http://www.riptutorial.com/ 78
Chapter 26: Render Best Practises
Introduction
Topic for important notes about specific Component.render method behavoir.
Examples
Functions in JSX
For better performance it's important to avoid using of array (lambda) function in JSX.
As explained at https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-
bind.md :
A bind call or arrow function in a JSX prop will create a brand new function on every
single render. This is bad for performance, as it will result in the garbage collector
being invoked way more than is necessary. It may also cause unnecessary re-renders
if a brand new function is passed as a prop to a component that uses reference
equality check on the prop to determine if it should update.
<TextInput
onChangeValue={ value => this.handleValueChanging(value) }
/>
or
<TextInput
onChangeValue={ this.handleValueChanging }
/>
and
For correct context within handleValueChanging function you can apply it in constructor of
component:
constructor(){
this.handleValueChanging = this.handleValueChanging.bind(this)
http://www.riptutorial.com/ 79
}
@autobind
handleValueChanging(newValue)
{
//processing event
}
http://www.riptutorial.com/ 80
Chapter 27: Routing
Introduction
Routing or navigation allows applications to between different screens. Its vital to a mobile app as
it provides context to user about where they are, decouple user actions between screens and
move between them, provide a state machine like model of the whole app.
Examples
Navigator component
Routes to Navigator are provided as objects. You also provide a renderScene function that renders
the scene for each route object. initialRoute is used to specify the first route.
http://www.riptutorial.com/ 81
Chapter 28: Run an app on device (Android
Version)
Remarks
Troubleshootings :
Could not connect to development server=> Do this : adb reverse tcp:8081 tcp:8081, make sure that
your phone is connected (adb devices). Verify also that there is a local server launched, if not run
react-native start
Examples
Running an app on Android Device.
1. adb devices
• Is your phone displaying? If not, enable developer mode on your phone, and connect it
by USB.
2. adb reverse tcp:8081 tcp:8081 :
• In order to link correctly your phone and that React-Native recognize him during build. (
NOTE:Android Version 5 or above.)
3. react-native run-android :
• To run the app on your phone.
4. react-native start :
• In order to start a local server for development (mandatory). This server is
automatically started if you use the last version of React-native.
http://www.riptutorial.com/ 82
Chapter 29: State
Syntax
• void setState( function|object nextState, [function callback] )
Examples
setState
To change view in your application you can use setState - this will re-render your component and
any of its child components. setState performs a shallow merge between the new and previous
state, and triggers a re-render of the component.
setState takes either a key-value object or a function that returns a key-value object
Key-Value Object
this.setState({myKey: 'myValue'});
Function
Using a function is useful for updating a value based off the existing state or props.
You can also pass an optional callback to setState that will be fired when the component has re-
rendered with the new state.
Full Example
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
http://www.riptutorial.com/ 83
this.state = {
myInteger: 0
}
}
getRandomInteger() {
const randomInt = Math.floor(Math.random()*100);
this.setState({
myInteger: randomInt
});
}
incrementInteger() {
}
render() {
</View>
}
}
}
}
http://www.riptutorial.com/ 84
</View>
</TouchableOpacity>
}
}
Initialize State
You should initialize state inside the constructor function of your component like this:
this.state = {
myInteger: 0
}
}
render() {
return (
<View>
<Text>Integer: {this.state.myInteger}</Text>
</View>
)
}
}
http://www.riptutorial.com/ 85
Chapter 30: Styling
Introduction
Styles are defined within a JSON object with similar styling attribute names like in CSS. Such an
object can either be put inline in the style prop of a component or it can be passed to the function
StyleSheet.create(StyleObject) and be stored in a variable for shorter inline access by using a
selector name for it similar to a class in CSS.
Syntax
• <Component style={styleFromStyleSheet} />
• <Component style={styleObject} />
• <Component style={[style1,style2]} />
Remarks
Most React Native styles are their CSS forms, but in camel case. So, text-decoration becomes
textDecoration.
Unlike in CSS, styles do not get inherited. If you want child components to inherit a certain style,
you must explicitly provide it to the child. This means that you cannot set a font family for an entire
View.
The one exception to this is the Text component: nested Texts inherit their parent styles.
Examples
Styling using inline styles
Each React Native component can take a style prop. You can pass it a JavaScript object with
CSS-style style properties:
This can be inefficient as it has to recreate the object each time the component is rendered. Using
a stylesheet is preferred.
http://www.riptutorial.com/ 86
},
big: {
fontSize: 30
}
});
returns an object where the values are numbers. React Native knows to
StyleSheet.create()
convert these numeric IDs into the correct style object.
You can pass an array to the style prop to apply multiple styles. When there is a conflict, the last
one in the list takes precedence.
Conditional Styling
http://www.riptutorial.com/ 87
<View style={[(this.props.isTrue) ? styles.bgcolorBlack : styles.bgColorWhite]}>
If the value of isTrue is true then it will have black background color otherwise white.
http://www.riptutorial.com/ 88
Chapter 31: Unit Testing
Introduction
Unit testing is a low level testing practice where smallest units or components of the code are
tested.
Examples
Unit testing with jest
Jestis a javascript testing framework widely used for testing react applications. Its supported by
facebook
Here's a test
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
http://www.riptutorial.com/ 89
</View>
);
}
}
Starting from react-native version 0.38, a Jest setup is included by default when running react-
native init. The following configuration should be automatically added to your package.json file:
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"jest": {
"preset": "react-native"
}
You can run run npm test or jest to test in react native. For code example: Link
http://www.riptutorial.com/ 90
Chapter 32: WebView
Introduction
Webview can be used to load external webpages or html content. This component is there by
default.
Examples
Simple component using webview
http://www.riptutorial.com/ 91
Credits
S.
Chapters Contributors
No
Create a shareable
6 Aditya Singh
APK for android
ESLint in react-
9 Alex Belets
native
Integration with
13 Firebase for Ankit Sinha, corasan
Authentication
http://www.riptutorial.com/ 92
16 ListView Kaleb Portillo
Multiple props
18 Jigar Shah
rendering
Navigator Best
20 Ankit Sinha, Michael Helvey, Pankaj Thakur
Practices
Navigator with
21 buttons injected from Ahmed Al Haddad
pages
RefreshControl with
25 Abdulaziz Alkharashi
ListView
Render Best
26 Alex Belets
Practises
Run an app on
28 device (Android Jagadish Upadhyay, Lwin Kyaw Myat, Mayeul
Version)
http://www.riptutorial.com/ 93