Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
React Native
Rafie Tarabay
eng_rafie@mans.edu.eg
What is react native is?
 React Native libraries were announced by Facebook in 2015,
providing the React architecture to native iOS, Android and
Universal Windows Platform applications.
 Framework for build mobile apps
 Build cross platform apps
 React native apps are not hybrid apps
 React native not run inside a webView
 Faster than Cordova/PhoneGap/ Ionic
 Open Source
 Develop using java script
 Application has the same look & feel of the same native
apps.
React native performance
Performance in calculations
http://browniefed.com/blog/react-native-how-to-create-twitter-exploding-hearts/
How to start
 Download and install Node JS (~ 12 MB)
https://nodejs.org/en/
 Download React Libraries [Shell command]
npm install -g react-native-cli
 Download Yarn [Optinal],
npm install –g yarn
(increase create new project performance by cache packages)
https://yarnpkg.com/en/
 Development IDE (Visual Studio Code) (~34 MB)
https://code.visualstudio.com/
 React extension tools to the IDE
https://marketplace.visualstudio.com/items?itemName=vsmobile.vscode-react-native
 Install Genymotion simulator
 http://dl.genymotion.com/releases/genymotion-2.9.0/genymotion-2.9.0.exe
Start First project
Create new project with name “myProject1” in the
current active directory [Shell Commands]
react-native init myProject1
cd myProject1
react-native start to compile
React-native run-android to run on device
React-native run-ios
React-native log-android to get console.log
React-native-cli VS react-native init
React Native is distributed as two npm packages
1)react-native-cli 
a lightweight package that should be installed
globally
npm install -g react-native-cli
2)react-native
contains the actual React Native framework
code and is installed locally into your project
when you run 
react-native init
Notes
To test your project you will need:
For Windows
 Android Studio
 Android SDK (6.0)
 Simulator
For IOS
 Xcode
 Simulator
Another solution
How to learn and test react-native applications
without install anything on your machine ?
Develop online, Test on mobile
 Visit https://snack.expo.io/
 Download the Expo app on your mobile
 Scan the QR code through Expo
application
 You are ready now!
Develop on machine, Test on mobile
Download Expo mobile application https://expo.io/
Create new React native application using the next
shell commands
 npm i -g create-react-native-app
 create-react-native-app myProject2
 cd myProject2
 npm start (to run in simulator: npm run android)
you will get QR code, scan it with Expo mobile app and you will
be ready!
For more information visit:
https://github.com/react-community/create-react-native-app
React native
How to install more libraries?
For navigation between pages
npm install react-native-router-flux --save
For GUI
npm i react-native-vector-icons --save
npm i react-native-material-ui --save
Run the next commands as administrator
Common Errors
Unable to resolve module
error
You may get packaging issue and you can
refresh all downloaded packages using the
next steps:
1.npm cache clean
2.delete ./node_modules
3.delete %temp%/react-*
4.npm install
error: bundling: NotFoundError: Cannot
find entry file index.android.js
Run the next two commands in orders will fix
this issues:
1 、 react-native start
2 、 react-native run-android
Need newer React-Native
$ npm uninstall -g react-native-cli
$ npm install -g react-native-cli
$ react-native init AwesomeApp
React-Native Facts
• Coding using ES6
• To compile, we need Xcode (for iOS, on Mac only) or Android
Studio (for Android) installed on your computer.
• React-Native doesn’t use HTML to render the app, but
provides alternative components that work in a similar way.
Those React-Native components map the actual real native
iOS or Android UI components that get rendered on the app.
What is ES6?
 ECMAScript 6 (new java script that support OOP)
 For web development, ES6 is finalized, but
not fully supported by all browsers. To use
ES6 today, get a compiler like Babel.
ES6 OOP Examples
React native
EC6
// example 1
([param] [, param]) => {
statements
}
// example 2
param => expression
Old JS
// example 1
function ([param] [, param]) {
statements
}
// example 2
function (param) {
return expression
}
Notes:
1) Arrow functions are always anonymous, but , we could assign our anonymous arrow
function it to a variable like this var doSomething = () => {statements; }
2) this in old JS refer to current function, while in arrow function inherits ‘this’ and
‘arguments’ from the context directly surrounding it, which is good for callback .
ES6 modules
 ES6 modules are stored in files. There is exactly one
module per file and one file per module.
 Modules are singletons. Even if a module is imported
multiple times, only a single “instance” of it exists.
 Top-level variables are local to module
 Modules Executed asynchronously.
Multiple named exports
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) { return x * x;}
export function diag(x, y) { return sqrt(square(x) + square(y));}
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import the complete module:
//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Single default export
There can be a single default export.
//------ myFunc.js ------
export default function () { ··· } // no semicolon!
//------ main1.js ------
import myFunc from 'myFunc';
myFunc();
========================================================
//------ MyClass.js ------
export default class { ··· } // no semicolon!
//------ main2.js ------
import MyClass from 'MyClass';
const inst = new MyClass();
Note there is no semicolon at the end if you default-export a function or a class
React native
React native
Let and Const
 let is a new var which allows to scope the variable to the blocks.
We define blocks by the curly braces.
 const, it’s just an immutable, and it’s also block-scoped like let.
spread syntax […x]
The spread syntax allows an expression to be expanded in places
where multiple arguments (for function calls) or multiple elements
(for array literals) or multiple variables (for destructuring assignment)
are expected.
For-of Iterator
use .map with Array
async/await
const getAllCategories = async () => {
const results = await fetch(categoriesURL)
const categories = await results.json()
return categories;
}
const getCategoryProducts = async (id) => {
const results = await fetch(productsURL + id)
const products = await results.json()
return products;
}
async componentDidMount() {
const categories = await getAllCategories();
}
End ES6
React Native basics
React native components vs HTML
React Native HTML
<View >Div
>Text >P
>TouchableOpacity onPress= >a href
>Image source= >img src=
>TextInput onChangeText= >input type=text onChange=
<Button onPress = {handlePress} title = "Red button!" /> >input type=button/<
>Picker onValueChange = {this.fn1} mode="dialog">
<Picker.Item label="red" value="red" />
</Picker<
<select onChange=‘’>
<option value=‘red’> red<option>
</select>
Sample React Native Code
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.intro}>Hello world!</Text>
</View>
);
}
}
Components stylesheets
To style your React-Native components, you will have to create stylesheets in
Javascript. It looks similar to CSS, but it’s not the same.
Sample CSS
const styles = StyleSheet.create({
container: { flex: 1, },
content: { backgroundColor: '#fff', padding: 30, },
button: { alignSelf: 'center', marginTop: 20, width: 100, },
image: { width: 40,height: 40,marginRight: 6, borderRadius: 20 }
});
How to use
<View style={styles.container} > zzz </View>
CSS tips
• Inline style
<view style={{backgroundColor:’#ff0000’}}>
ggggg
</view>
• Inline style + Normal style
<view
style={[styles.container, {color: 'white', backgroundColor: '#333'}]} > …
</view>
• Two Styles
<view style={[ styles.container , styles.style1 ]} > …
</view>
• Style depend on platform
{marginTop: Platform.OS == 'android' ? 22 : 0}
React Native flex layout
• flex: 1;  container will expand full available width
Left image {flex: 1}, Right image—no flex declaration   
Flex related to each others
Flex related to each others
flexDirection: ‘row’ vs flexDirection: ‘column’
Flex main axis in ‘row’ and
‘column’
row column
justifyContent
• determines the distribution of children along the main axis.
• Available options are flex-start, center, flex-end, space-
around, and space-between.
alignItems
• determines the alignment of children along the secondary axis (if the
primary axis is row, then the secondary is column, and vice versa).
• Available options are flex-start, center, flex-end, and stretch.
Justify-content property will always align content along Main Axis.
Align-items property will always align content along Cross Axis.
React native
React native
Events
 onPress
 onChangeText
 onSubmitEditing
 PanResponder
Touch events
• Touch event called PanResponder
• onPanResponderGrant (touchstart)
• onPanResponderMove  (touchmove)
• onPanResponderRelease  (touchend)
PanResponder parameters
onPanResponderMove: (event, gestureState) => {}
nativeEvent
changedTouches - Array of all touch events that have
changed since the last event
identifier - The ID of the touch
locationX - X position of the touch, relative to element
locationY - Y position of the touch, relative to element
pageX - X position of the touch, relative to root element
pageY - Y position of the touch, relative to root element
target - node id of the element receiving the touch event
timestamp - A time identifier for the touch
touches - Array of all current touches on the screen
gestureState :
stateID - ID of the gestureState- persisted as long as
there at least one touch on screen
moveX - the latest screen coordinates of the
recently-moved touch
moveY - the latest screen coordinates of the
recently-moved touch
x0 - the screen coordinates of the responder grant
y0 - the screen coordinates of the responder grant
dx - accumulated distance since the touch started
dy - accumulated distance since the touch started
vx - current velocity of the gesture
vy - current velocity of the gesture
numberActiveTouches - Number of touches currently
on screen
Example 1
Image, Button
<Image
source= {{uri:’’}} vs {require(‘’)}
<Image
source = {{ uri: 'https://eulc.edu.eg/1.png' }}
style = {{ width: 200, height: 200 }}
/>
<Image source = {require('../../img/myImage.png')} />
Style
image: { width: 40,height: 40,marginRight: 6, borderRadius: 20 }
Button
<Button
onPress = {handlePress}
title = "Red button!"
color = "red"
/>
Example 2
Import
Load the content of page from another
page
React native
React native
Notes
The import name can be anything but the first
letter of import class name should be capital,
otherwise you will get error.
import Demo from './demo/demo'
…..
<View>
<Demo />
</View>
Example 3
this.props
pass parameter from Page1 to Page2
React native
React native
Example 4
Constructor, this.state, and this.props
React native
Example 5
 setState, TextInput
 Use props to call function
React native
React native
Example 6
Using conditions and let
React native
React native
Example 7
 Using ScrollView, const, and .map
React native
React native
Example 8
defaultProps, pass props to constructor
React native
Difference between State and Props
 state can be updated in the future while
props can't.
Picker mode(dropdown/ dialog)
<Picker
style={styles.picker}
selectedValue={this.state.color}
onValueChange = {this.updateColor}
mode="dialog">
<Picker.Item label="red" value="red" />
<Picker.Item label="green" value="green" />
<Picker.Item label="blue" value="blue" />
</Picker>
constructor() {
super();
this.state = {color: ''};
}
updateColor = (color1) => {
this.setState({color: color1});
}
Navigate to another page
 Install the next component in the same project path
npm install react-native-router-flux --save
<Router>
<Scene key = "root">
<Scene key = "page0" component = {Page0} title = "Home" initial = {true} />
<Scene key = "page1" component = {Page1} title = "About" />
</Scene>
</Router>
- To Set the default load page set initial = {true}
- The new page upper title is defined using title
- To dynamic set title, replace title with getTitle, getTitle={props => props.name}
- To load page without title hideNavBar={true}
- To navigate to another page set Actions.key,
and the page that will load are defined in component
<Button onPress={Actions.page1} title="Page0" />
Navigation Page
Page 0
Page 1
Example 9
componentDidMount, alert
React native
React native
ListView
ListView should be used for large lists because it renders
only elements visible on screen.
ListView main components
dataSource will be used as a model to our list. We will
create it in our container component.
renderRow will take each element from dataSource array
and render it on screen. Since it renders elements, we will
use it in presentational component.
rowHasChanged is function used to determine when the
row has changed.
Simple ListView Example
Example 10
Render row in another function
import React, { Component } from 'react';
import { ListView, Text, View, Alert, TouchableOpacity } from 'react-native';
export default class App extends Component {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = { dataSource: ds.cloneWithRows([ 'Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6', 'Item7']) };
}
renderItem = (rowData) => {
return ( <TouchableOpacity onPress= { () => {alert(rowData); }}>
<View > <Text>{rowData}</Text> </View>
</TouchableOpacity> ) }
render() {
return (
<View>
<ListView dataSource={this.state.dataSource} renderRow={this.renderItem} />
</View>);
}
}
Example 11
Load json data online
React native
Example 12
Post data to server
Solution 1
let data = new FormData();
data.append("useremail", ‘name@site.com');
data.append("userpassword", '1234');
fetch('http://URL',
{
method: 'POST',
headers: {
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}) .then((response) => response.json())
.then((responseJson) => { Alert.alert( 'Alert Title', responseJson.output ) })
.catch((error) => {
console.error(error);
});
Solution 2
fetch('http://localhost:3000/auth', {
method: 'post',
body: JSON.stringify({
config_name: 'default',
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,})
}) .then((response) => response.json())
.then((responseJson) => { Alert.alert( 'Alert Title',
responseJson.output ) })
.catch((error) => {
console.error(error);
});
Save/Load data from local storage
Save/Get String data (only) from local storage.
import { AsyncStorage } from 'react-native‘
AsyncStorage.setItem('key', 'value');
AsyncStorage.getItem('key');
AsyncStorage.setItem(‘key', JSON.stringify(value));
AsyncStorage.getItem('key').json();
Save/Load data from local storage
Maps
It is native component for IOS but for android you should register on google
API and get key and download extension to support that!
•npm install react-native-maps --save
•react-native link react-native-maps
•Ensure that you have Google Play Services installed, for Genymotion
download Nano X86 from http://opengapps.org/ then drug the zip package
to the android simulator version.
•you need to get a google API Key
https://console.developers.google.com/apis/credentials
•Add your API key to your manifest file
(androidappsrcmainAndroidManifest.xml):
<application>
<!-- You will only need to add this meta-data tag, but make sure it's a child of application -->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="Your Google maps API Key Here"/>
</application>
Complete Solution
Application Description
Two pages
•First one get list of data from Rest API and view
it, when user click on any row navigate to
second page
•Second page get the selected row info and
Query another Rest API to view the details.
React native
First page REST API
URL : http://fake-api.a.malsapp.com/category
Sample Response
[
{ "id": 1, "name": "vestibulum sed" },
{ "id": 2, "name": "pretium ac" },
{ "id": 3, "name": "facilisis ipsum" },
{ "id": 4, "name": "sollicitudin sagittis" }
]
Second page REST API
URL : http://fake-api.a.malsapp.com/product?category_id=1
Sample Response
[
{ "id": 3, "category_id": 1,
"name": "tempor mattis mattis",
"description": "mi sollicitudin nec et lectus",
"price": 370},
{ "id": 17,
"category_id": 1,
"name": "fringilla vel curabitur",
"description": "mattis eros eros id quis pulvinar nec",
"price": 224 }
]
React native
React native
React native
React native
React native
React native
React native
React native
What is the best UI Kit for react native?
NativeBase
A huge collection of components, most of which look quite nice. That’s the plus side. The down side is that
some of the components are somewhat buggy.
React Native Elements
The styling is generally platform agnostic; it won’t look out of place using it on either Android or iOS. Each
component has simple customization, the docs are solid, and it comes with a good set of icons. This is a
no-brainer.
React Native Material Design
Another solid choice, but mostly only useful for Android. Again, its a bit unsettling to see material design -
traditionally a stable of Android devices - on iOS. Besides that, the docs are still a work in progress, as
evidenced by the lack of docs for nearly half of the components. Nonetheless, if you’re looking for a
material design solution, this is better than nothing. It is also worth noting that the project looks generally
unmaintained.
React Native Material Kit
Another material design solution, but much better maintained than React Native Material Design. This one
has the added benefit of a nicer customization API for creating your own custom components - see the
docs on this. It also has some more dynamic components like progress bars and sliders, which you may not
see on other frameworks. Anything that helps save you time to build your app is always a solid benefit.
Nativebase
We need Nativebase for better GUI
open VS IDE then Ctrl+P and type
ext install nativebase-snippets
To add Nativebase to the current project
npm install native-base --save
react-native link
Samples of GUI designs
using Nativebase
React native
Android IOS
How to learn Nativebase?
 For more information about Nativebase
https://docs.nativebase.io/Components.html#Drawer
 For Complete sample project
https://github.com/GeekyAnts/NativeBase-
KitchenSink
Resources
Setup your machine for React-native
https://www.youtube.com/watch?v=KRLLjlpy0r4
Tutorial https://www.tutorialspoint.com/react_native/
List of new components https://js.coach/react-native
Online session https://www.youtube.com/watch?v=mkualZPRZCs
ES6 http://es6-features.org/
React GUI components
https://docs.nativebase.io/Components.html#Drawer
https://github.com/xotahal/react-native-material-ui
http://react-native-material-design.github.io/
https://react-native-training.github.io/react-native-elements/
Complete UI Example using NativeBase
https://github.com/GeekyAnts/NativeBase-KitchenSink
Books (free for Egyptian only)
 React Native for iOS Development
https://link.springer.com/book/10.1007%2F978-1-
4842-1395-7
 Introduction to React
https://link.springer.com/book/10.1007%2F978-1-
4842-1245-5
 Pro React
https://link.springer.com/book/10.1007%2F978-1-
4842-1260-8

More Related Content

React native

  • 2. What is react native is?  React Native libraries were announced by Facebook in 2015, providing the React architecture to native iOS, Android and Universal Windows Platform applications.  Framework for build mobile apps  Build cross platform apps  React native apps are not hybrid apps  React native not run inside a webView  Faster than Cordova/PhoneGap/ Ionic  Open Source  Develop using java script  Application has the same look & feel of the same native apps.
  • 5. How to start  Download and install Node JS (~ 12 MB) https://nodejs.org/en/  Download React Libraries [Shell command] npm install -g react-native-cli  Download Yarn [Optinal], npm install –g yarn (increase create new project performance by cache packages) https://yarnpkg.com/en/  Development IDE (Visual Studio Code) (~34 MB) https://code.visualstudio.com/  React extension tools to the IDE https://marketplace.visualstudio.com/items?itemName=vsmobile.vscode-react-native  Install Genymotion simulator  http://dl.genymotion.com/releases/genymotion-2.9.0/genymotion-2.9.0.exe
  • 6. Start First project Create new project with name “myProject1” in the current active directory [Shell Commands] react-native init myProject1 cd myProject1 react-native start to compile React-native run-android to run on device React-native run-ios React-native log-android to get console.log
  • 7. React-native-cli VS react-native init React Native is distributed as two npm packages 1)react-native-cli  a lightweight package that should be installed globally npm install -g react-native-cli 2)react-native contains the actual React Native framework code and is installed locally into your project when you run  react-native init
  • 8. Notes To test your project you will need: For Windows  Android Studio  Android SDK (6.0)  Simulator For IOS  Xcode  Simulator
  • 9. Another solution How to learn and test react-native applications without install anything on your machine ?
  • 10. Develop online, Test on mobile  Visit https://snack.expo.io/  Download the Expo app on your mobile  Scan the QR code through Expo application  You are ready now!
  • 11. Develop on machine, Test on mobile Download Expo mobile application https://expo.io/ Create new React native application using the next shell commands  npm i -g create-react-native-app  create-react-native-app myProject2  cd myProject2  npm start (to run in simulator: npm run android) you will get QR code, scan it with Expo mobile app and you will be ready! For more information visit: https://github.com/react-community/create-react-native-app
  • 13. How to install more libraries? For navigation between pages npm install react-native-router-flux --save For GUI npm i react-native-vector-icons --save npm i react-native-material-ui --save Run the next commands as administrator
  • 15. Unable to resolve module error You may get packaging issue and you can refresh all downloaded packages using the next steps: 1.npm cache clean 2.delete ./node_modules 3.delete %temp%/react-* 4.npm install
  • 16. error: bundling: NotFoundError: Cannot find entry file index.android.js Run the next two commands in orders will fix this issues: 1 、 react-native start 2 、 react-native run-android
  • 17. Need newer React-Native $ npm uninstall -g react-native-cli $ npm install -g react-native-cli $ react-native init AwesomeApp
  • 18. React-Native Facts • Coding using ES6 • To compile, we need Xcode (for iOS, on Mac only) or Android Studio (for Android) installed on your computer. • React-Native doesn’t use HTML to render the app, but provides alternative components that work in a similar way. Those React-Native components map the actual real native iOS or Android UI components that get rendered on the app.
  • 19. What is ES6?  ECMAScript 6 (new java script that support OOP)  For web development, ES6 is finalized, but not fully supported by all browsers. To use ES6 today, get a compiler like Babel.
  • 22. EC6 // example 1 ([param] [, param]) => { statements } // example 2 param => expression Old JS // example 1 function ([param] [, param]) { statements } // example 2 function (param) { return expression } Notes: 1) Arrow functions are always anonymous, but , we could assign our anonymous arrow function it to a variable like this var doSomething = () => {statements; } 2) this in old JS refer to current function, while in arrow function inherits ‘this’ and ‘arguments’ from the context directly surrounding it, which is good for callback .
  • 23. ES6 modules  ES6 modules are stored in files. There is exactly one module per file and one file per module.  Modules are singletons. Even if a module is imported multiple times, only a single “instance” of it exists.  Top-level variables are local to module  Modules Executed asynchronously.
  • 24. Multiple named exports //------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x;} export function diag(x, y) { return sqrt(square(x) + square(y));} //------ main.js ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5 You can also import the complete module: //------ main.js ------ import * as lib from 'lib'; console.log(lib.square(11)); // 121 console.log(lib.diag(4, 3)); // 5
  • 25. Single default export There can be a single default export. //------ myFunc.js ------ export default function () { ··· } // no semicolon! //------ main1.js ------ import myFunc from 'myFunc'; myFunc(); ======================================================== //------ MyClass.js ------ export default class { ··· } // no semicolon! //------ main2.js ------ import MyClass from 'MyClass'; const inst = new MyClass(); Note there is no semicolon at the end if you default-export a function or a class
  • 28. Let and Const  let is a new var which allows to scope the variable to the blocks. We define blocks by the curly braces.  const, it’s just an immutable, and it’s also block-scoped like let.
  • 29. spread syntax […x] The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
  • 31. use .map with Array
  • 32. async/await const getAllCategories = async () => { const results = await fetch(categoriesURL) const categories = await results.json() return categories; } const getCategoryProducts = async (id) => { const results = await fetch(productsURL + id) const products = await results.json() return products; } async componentDidMount() { const categories = await getAllCategories(); }
  • 35. React native components vs HTML React Native HTML <View >Div >Text >P >TouchableOpacity onPress= >a href >Image source= >img src= >TextInput onChangeText= >input type=text onChange= <Button onPress = {handlePress} title = "Red button!" /> >input type=button/< >Picker onValueChange = {this.fn1} mode="dialog"> <Picker.Item label="red" value="red" /> </Picker< <select onChange=‘’> <option value=‘red’> red<option> </select>
  • 36. Sample React Native Code import React, { Component } from 'react'; import { View, Text } from 'react-native'; export default class App extends Component { render() { return ( <View style={styles.container}> <Text style={styles.intro}>Hello world!</Text> </View> ); } }
  • 37. Components stylesheets To style your React-Native components, you will have to create stylesheets in Javascript. It looks similar to CSS, but it’s not the same. Sample CSS const styles = StyleSheet.create({ container: { flex: 1, }, content: { backgroundColor: '#fff', padding: 30, }, button: { alignSelf: 'center', marginTop: 20, width: 100, }, image: { width: 40,height: 40,marginRight: 6, borderRadius: 20 } }); How to use <View style={styles.container} > zzz </View>
  • 38. CSS tips • Inline style <view style={{backgroundColor:’#ff0000’}}> ggggg </view> • Inline style + Normal style <view style={[styles.container, {color: 'white', backgroundColor: '#333'}]} > … </view> • Two Styles <view style={[ styles.container , styles.style1 ]} > … </view> • Style depend on platform {marginTop: Platform.OS == 'android' ? 22 : 0}
  • 39. React Native flex layout • flex: 1;  container will expand full available width Left image {flex: 1}, Right image—no flex declaration   
  • 40. Flex related to each others
  • 41. Flex related to each others
  • 42. flexDirection: ‘row’ vs flexDirection: ‘column’
  • 43. Flex main axis in ‘row’ and ‘column’ row column
  • 44. justifyContent • determines the distribution of children along the main axis. • Available options are flex-start, center, flex-end, space- around, and space-between.
  • 45. alignItems • determines the alignment of children along the secondary axis (if the primary axis is row, then the secondary is column, and vice versa). • Available options are flex-start, center, flex-end, and stretch.
  • 46. Justify-content property will always align content along Main Axis. Align-items property will always align content along Cross Axis.
  • 49. Events  onPress  onChangeText  onSubmitEditing  PanResponder
  • 50. Touch events • Touch event called PanResponder • onPanResponderGrant (touchstart) • onPanResponderMove  (touchmove) • onPanResponderRelease  (touchend)
  • 51. PanResponder parameters onPanResponderMove: (event, gestureState) => {} nativeEvent changedTouches - Array of all touch events that have changed since the last event identifier - The ID of the touch locationX - X position of the touch, relative to element locationY - Y position of the touch, relative to element pageX - X position of the touch, relative to root element pageY - Y position of the touch, relative to root element target - node id of the element receiving the touch event timestamp - A time identifier for the touch touches - Array of all current touches on the screen gestureState : stateID - ID of the gestureState- persisted as long as there at least one touch on screen moveX - the latest screen coordinates of the recently-moved touch moveY - the latest screen coordinates of the recently-moved touch x0 - the screen coordinates of the responder grant y0 - the screen coordinates of the responder grant dx - accumulated distance since the touch started dy - accumulated distance since the touch started vx - current velocity of the gesture vy - current velocity of the gesture numberActiveTouches - Number of touches currently on screen
  • 53. <Image source= {{uri:’’}} vs {require(‘’)} <Image source = {{ uri: 'https://eulc.edu.eg/1.png' }} style = {{ width: 200, height: 200 }} /> <Image source = {require('../../img/myImage.png')} /> Style image: { width: 40,height: 40,marginRight: 6, borderRadius: 20 }
  • 54. Button <Button onPress = {handlePress} title = "Red button!" color = "red" />
  • 56. Load the content of page from another page
  • 59. Notes The import name can be anything but the first letter of import class name should be capital, otherwise you will get error. import Demo from './demo/demo' ….. <View> <Demo /> </View>
  • 61. pass parameter from Page1 to Page2
  • 66. Example 5  setState, TextInput  Use props to call function
  • 72. Example 7  Using ScrollView, const, and .map
  • 75. Example 8 defaultProps, pass props to constructor
  • 77. Difference between State and Props  state can be updated in the future while props can't.
  • 78. Picker mode(dropdown/ dialog) <Picker style={styles.picker} selectedValue={this.state.color} onValueChange = {this.updateColor} mode="dialog"> <Picker.Item label="red" value="red" /> <Picker.Item label="green" value="green" /> <Picker.Item label="blue" value="blue" /> </Picker> constructor() { super(); this.state = {color: ''}; } updateColor = (color1) => { this.setState({color: color1}); }
  • 79. Navigate to another page  Install the next component in the same project path npm install react-native-router-flux --save <Router> <Scene key = "root"> <Scene key = "page0" component = {Page0} title = "Home" initial = {true} /> <Scene key = "page1" component = {Page1} title = "About" /> </Scene> </Router> - To Set the default load page set initial = {true} - The new page upper title is defined using title - To dynamic set title, replace title with getTitle, getTitle={props => props.name} - To load page without title hideNavBar={true} - To navigate to another page set Actions.key, and the page that will load are defined in component <Button onPress={Actions.page1} title="Page0" />
  • 86. ListView ListView should be used for large lists because it renders only elements visible on screen. ListView main components dataSource will be used as a model to our list. We will create it in our container component. renderRow will take each element from dataSource array and render it on screen. Since it renders elements, we will use it in presentational component. rowHasChanged is function used to determine when the row has changed.
  • 88. Example 10 Render row in another function
  • 89. import React, { Component } from 'react'; import { ListView, Text, View, Alert, TouchableOpacity } from 'react-native'; export default class App extends Component { constructor() { super(); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([ 'Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6', 'Item7']) }; } renderItem = (rowData) => { return ( <TouchableOpacity onPress= { () => {alert(rowData); }}> <View > <Text>{rowData}</Text> </View> </TouchableOpacity> ) } render() { return ( <View> <ListView dataSource={this.state.dataSource} renderRow={this.renderItem} /> </View>); } }
  • 90. Example 11 Load json data online
  • 92. Example 12 Post data to server
  • 93. Solution 1 let data = new FormData(); data.append("useremail", ‘name@site.com'); data.append("userpassword", '1234'); fetch('http://URL', { method: 'POST', headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded', }, body: data }) .then((response) => response.json()) .then((responseJson) => { Alert.alert( 'Alert Title', responseJson.output ) }) .catch((error) => { console.error(error); });
  • 94. Solution 2 fetch('http://localhost:3000/auth', { method: 'post', body: JSON.stringify({ config_name: 'default', first_name: this.state.first_name, last_name: this.state.last_name, email: this.state.email,}) }) .then((response) => response.json()) .then((responseJson) => { Alert.alert( 'Alert Title', responseJson.output ) }) .catch((error) => { console.error(error); });
  • 95. Save/Load data from local storage Save/Get String data (only) from local storage. import { AsyncStorage } from 'react-native‘ AsyncStorage.setItem('key', 'value'); AsyncStorage.getItem('key'); AsyncStorage.setItem(‘key', JSON.stringify(value)); AsyncStorage.getItem('key').json();
  • 96. Save/Load data from local storage
  • 97. Maps It is native component for IOS but for android you should register on google API and get key and download extension to support that! •npm install react-native-maps --save •react-native link react-native-maps •Ensure that you have Google Play Services installed, for Genymotion download Nano X86 from http://opengapps.org/ then drug the zip package to the android simulator version. •you need to get a google API Key https://console.developers.google.com/apis/credentials •Add your API key to your manifest file (androidappsrcmainAndroidManifest.xml): <application> <!-- You will only need to add this meta-data tag, but make sure it's a child of application --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="Your Google maps API Key Here"/> </application>
  • 99. Application Description Two pages •First one get list of data from Rest API and view it, when user click on any row navigate to second page •Second page get the selected row info and Query another Rest API to view the details.
  • 101. First page REST API URL : http://fake-api.a.malsapp.com/category Sample Response [ { "id": 1, "name": "vestibulum sed" }, { "id": 2, "name": "pretium ac" }, { "id": 3, "name": "facilisis ipsum" }, { "id": 4, "name": "sollicitudin sagittis" } ]
  • 102. Second page REST API URL : http://fake-api.a.malsapp.com/product?category_id=1 Sample Response [ { "id": 3, "category_id": 1, "name": "tempor mattis mattis", "description": "mi sollicitudin nec et lectus", "price": 370}, { "id": 17, "category_id": 1, "name": "fringilla vel curabitur", "description": "mattis eros eros id quis pulvinar nec", "price": 224 } ]
  • 111. What is the best UI Kit for react native? NativeBase A huge collection of components, most of which look quite nice. That’s the plus side. The down side is that some of the components are somewhat buggy. React Native Elements The styling is generally platform agnostic; it won’t look out of place using it on either Android or iOS. Each component has simple customization, the docs are solid, and it comes with a good set of icons. This is a no-brainer. React Native Material Design Another solid choice, but mostly only useful for Android. Again, its a bit unsettling to see material design - traditionally a stable of Android devices - on iOS. Besides that, the docs are still a work in progress, as evidenced by the lack of docs for nearly half of the components. Nonetheless, if you’re looking for a material design solution, this is better than nothing. It is also worth noting that the project looks generally unmaintained. React Native Material Kit Another material design solution, but much better maintained than React Native Material Design. This one has the added benefit of a nicer customization API for creating your own custom components - see the docs on this. It also has some more dynamic components like progress bars and sliders, which you may not see on other frameworks. Anything that helps save you time to build your app is always a solid benefit.
  • 112. Nativebase We need Nativebase for better GUI open VS IDE then Ctrl+P and type ext install nativebase-snippets To add Nativebase to the current project npm install native-base --save react-native link
  • 113. Samples of GUI designs using Nativebase
  • 116. How to learn Nativebase?  For more information about Nativebase https://docs.nativebase.io/Components.html#Drawer  For Complete sample project https://github.com/GeekyAnts/NativeBase- KitchenSink
  • 117. Resources Setup your machine for React-native https://www.youtube.com/watch?v=KRLLjlpy0r4 Tutorial https://www.tutorialspoint.com/react_native/ List of new components https://js.coach/react-native Online session https://www.youtube.com/watch?v=mkualZPRZCs ES6 http://es6-features.org/ React GUI components https://docs.nativebase.io/Components.html#Drawer https://github.com/xotahal/react-native-material-ui http://react-native-material-design.github.io/ https://react-native-training.github.io/react-native-elements/ Complete UI Example using NativeBase https://github.com/GeekyAnts/NativeBase-KitchenSink
  • 118. Books (free for Egyptian only)  React Native for iOS Development https://link.springer.com/book/10.1007%2F978-1- 4842-1395-7  Introduction to React https://link.springer.com/book/10.1007%2F978-1- 4842-1245-5  Pro React https://link.springer.com/book/10.1007%2F978-1- 4842-1260-8