0% found this document useful (0 votes)
8 views64 pages

FirstProject App Installation Guide

The document provides a comprehensive guide for installing and configuring React Native on both Windows and Mac OS, detailing prerequisites and installation steps. It outlines standards for variable and function naming, project structure, and the lifecycle of components in React Native. Additionally, it includes instructions for starting a new project, handling common errors, and utilizing state and props effectively within components.

Uploaded by

tvh111004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views64 pages

FirstProject App Installation Guide

The document provides a comprehensive guide for installing and configuring React Native on both Windows and Mac OS, detailing prerequisites and installation steps. It outlines standards for variable and function naming, project structure, and the lifecycle of components in React Native. Additionally, it includes instructions for starting a new project, handling common errors, and utilizing state and props effectively within components.

Uploaded by

tvh111004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Installing, configuration, First project

1
PERQUISITES

• VISUAL STUDIO/XCODE
• ANDROID STUDIO
• SIMULATOR
NOTES
• Windows OS only build android applications.
• IoS OS can build android và ios applications.
• Ios lowest version that react-native can support is ios 8.0
• Android lowest version that React-native can support android 4.1 (api 16)
2
INSTALLING ON WINDOWS
• Step 1: install chocolatey from [Link] (chocolatey is a
windows package manager)
• Step 2: install nodejs java and python 2 via chocolatey using the following
command (use cmd to run this command):
Choco install -y [Link] python2 jdk8
• Step 3: install android studio
• Step 4: install SDK: it is recommended to install SDK platform 23 because by
default react-native currently uses android SDK platform 23 to build
applications 3
INSTALLING ON MAC OS
• Step 1: Install Brew: Brew is a secondary package manager, MAC OS does not have it
built-in and you must use the terminal to install brew by running the following command.
{{/usr/bin/ruby -e "$(curl –fsSL [Link]
Homebrew/install/master/install)"}}
• Step 2: Install Nodejs: brew install node
• Step 3: Install Watchman: brew install watchman
• Step 4: Install react-native: npm install -g react-native-cli
• Step 5: Install Xcode: go to the App Store on MACOS to install Xcode.
• Step 6 (optional): If you build an Android application using the MACOS operating system,
you need to install additional packages such as JDK, Android Studio, Android SDK. (see
4

the installation section for Windows for more details.)


STANDARDS RULES IN REACT NATIVE PROGRAMMING
• Variable name
Variable names must start with a lowercase letter.
Variable names cannot start with a number or special character.
The first letter of each word is capitalized.
Variable names must be meaningful.
If it is a style, the abbreviation of view should be added in front of it.
Ex:
maxNumber
minNumber
textMessageanswer
btnActionagree 5
STANDARDS RULES IN REACT NATIVE PROGRAMMING
• Funtion name
Function names also start with a lowercase letter.
Function names cannot contain special characters.
The first letter of each word is capitalized.
Function names must be clear and describe the function's function.
Ex:
indMinOfTowNumber(firstNumber, secondNumeber){}
onPressBtnLanguage(){}
onPressNegativeAction(){}

6
PROJECT STRUCTURE
Project directory structure model
• The entire source code of the program will be placed in the app directory
• assets is the directory containing my resources including resources such as
custom fonts (fonts), images (images), languages (languages)
• configs is the directory containing the application configurations: including
server configurations, links, basic colors.

7
PROJECT STRUCTURE
• libs is the directory containing my basic libraries to handle some internal issues such as:
o Database (processing data storage using database)
o Storage (processing data storage using storage)
o Language (Configuring multi-language processing in the application)
o RESTClient (Configuration, list of APIs accessing the server system)
o SoundPlayer (Controlling sound)
o Inapp (Some configurations, processing payments for purchases with the store)
o Ads (Configuring displaying advertisements from third parties)
• models is the directory containing models that I define, which can be defining objects or types of
objects
• modules is the directory containing modules that I define or customize. Including:
• screens - module containing all screen processing of the application
• views - module containing all customized views.
8
• And some modules that I want to edit from the library, can be added here for customization.
BEGINNING THE FIRST PROJECT
• Step 1: Initialize the project: open Terminal (cmd) then type this command (cd to the folder you want to create the project first)

react-native init firstProject


• Step 2: Access the newly created project. cd firstProject
• Step 3: compile project react-native start
• Step 4: Run the application on the operating system: IOS: react-native run-ios
Android: react-native run-android
• When running this command, the operating system will create a local server to build your react code. Along with that, run
the commands to build the application.
• You can also open the /ios/[Link] file with Xcode to launch the application, or open the entire android
folder with Android studio to launch the application.
• Display the Control Menu:
Command + D (or shake the IOS phone) to display the control menu when running debug applications on MacOS.
ctrl + D or the menu key to display the control menu when running debug applications on Windows.
9

• Command + R to reload the IOS virtual machine source code


• R + R to reload the Android virtual machine source code.
BEGINNING THE FIRST PROJECT
• some errors
Do not initialize the server to build when running debug on android then run
react-native start
When running Android without using the latest react-native code then run this
line (Build all your source into 1 file and put it in assets, create the
corresponding android resources that you use).
react-native bundle --platform android --dev false --entry-file [Link] --bundle-output
android/app/src/main/assets/[Link] --assets-dest android/app/src/main/res

10
BEGINNING THE FIRST PROJECT
• Some errors
When general APK has double resource error, delete drawable folder in
android/app/src/main/res then it will build.
When running ios app, error "Build input file cannot be found:
'../Example/node_modules/react-native/third-party/double-conversion-
1.1.6/src/[Link]'" then run the following 2 commands:
cd node_modules/react-native/scripts && ./[Link] && cd ../../../
cd node_modules/react-native/third-party/glog-0.3.5/ && ../../scripts/ios-configure-
[Link] && cd ../../../../

11
BEGINNING THE FIRST PROJECT
• Main components of project
Android folder: contains all the Android application build source. We
can open the Android folder with Android studio and run the application
instead of using the command line react-native run-android but the
application may not build the javascript code and a white screen will
appear on the Android phone.

IOS folder: contains all the IOS application build source. We can open
the [Link] file with Xcode to run the IOS application
instead of using the command line react-native run-ios.

12
BEGINNING THE FIRST PROJECT
• node_modules folder: contains all the packages (libraries) needed to run a react-native
application.
• File [Link]: file to manage the nodejs packages that come with the project. If you
download the demo projects, you need to use the npm install command line to download all
the required libraries of the project.
• File [Link] file is generalized after running the npm install installation
• File [Link]: the first file to be bound when running the application. This file will register a
component, this component will be loaded first when running, by default the application
will register the component in [Link]
• File [Link]: file to configure the application name and display name.
13

• File [Link] is a default component that uses some other Components such as Text, View...
COMPONENTS OF REACT NATIVE
• Life cycle of componetns

14
COMPONENTS OF REACT NATIVE
• Life cycle of components – the methods are called in the life of components
• constructor(props) - Component initialization function. In this function, we often use it to initialize
state, bind child functions of the component.
Note: Do not change state using [Link]() method in this function.
• componentWillMount() - This function will be removed in the new version.
• render() - This is a required function in the component. After initialization, this function is called to
return the components displayed on the screen.
• This function will be automatically called again when its state or props change. Only components
that use state or props will be called again to re-render.
Note:
• [Link]() method should not be used in this function.
• This function should not run a lot of data processing to avoid lag when rendering (data processing
15
should be done in componentDidMount or constructor).
COMPONENTS OF REACT NATIVE
• componentDidMount() - This function will be called right after the render() function is called for
the first time. Normally, in this function, we can get data from the server or client to render the data.
When running here, the components have been generated, we can interact with the UI components.
• componentWillReceiveProps(nextProps) - This function is called when the props of the initialized
component change.
• shouldComponentUpdate(nextProps, nextState) - This function is called before render() when
updating data. This function returns true or false. If false, the default render function will not be
called again, it returns true.
• componentWillUpdate(nextProps, nextState) - This function is called right after the
shouldComponentUpdate() function returns true. The state is not reset in this function.
• componentDidUpdate(prevProps, prevState) - This function is called right after the render()
function from the second time onwards.
• componentWillUnmount() - This function is called when this component is removed. We should
16
perform cleanup operations, cancel timers or processes in progress.
COMPONENTS OF REACT NATIVE
Ex1: sample code

import React, { Component } from 'react';

import { Text, View } from 'react-native';

export default class App extends Component {

constructor(props) {

super(props);

[Link] = {

message: "Welcome to Code 101 - React-native“ } }

render() {

return (

<View>

<Text>{[Link]}</Text>
17
</View>

); }}
COMPONENTS OF REACT NATIVE
• State - is a variable that controls the internal state of a component. State can be changed by
calling [Link]({...}). Each time the state changes, the render function will be called
again immediately (the render function only changes the components related to the
values in the changed state).
We should put variables related to the UI into this state, so that when the state changes, the
screen UI will be redrawn and changed accordingly.
Note: Do not change the state directly by calling [Link] = {...} if using direct state changes,
the entire component will no longer work as desired.
• Props - are properties passed in by the user. These are parameters passed in to customize
according to the wishes of the Component builder. Unlike state, we cannot change props in
itself. We should only read the properties passed in for use.
Example using props: same example above but we customize some things so you can
understand more about props 18
COMPONENTS OF REACT NATIVE
import React, { Component } from 'react';

import { Text, View } from 'react-native';

class CustomText extends Component {

constructor(props) {

super(props);

render() {

return ( <Text>{[Link]}</Text> /*using props is passed from out site.*/ );

}}

export default class App extends Component {

constructor(props) {

super(props);

[Link] = {

message: "Welcome to Code 101 - React-native"


19
} }

render() { return ( <CustomText message={[Link]} /> /*pass 1 props into sub class for use.*/ ); }}
SOME OF SPECIAL METHODS IN REACT NATIVE
• [Link]() - The function is used to change the state of the component. This is the main method
to update the user interface. When this function is finished executing, the render() function will be
automatically called again. If the state value changes, only the components that use the
corresponding state variable will be called to redraw the UI. Note: this function runs
asynchronously, so we should not read the value after calling this function.
[Link]({
message: “wellcome",
key: "Value",
})
Note: not use
[Link]([Link])
[Link] immediately using set method
20
The variable passed to the setState function is an object of the form key: value.
SOME OF SPECIAL METHODS IN REACT NATIVE
• Callback can be used to check data or handle some tasks after a state change.
[Link]({ message: “Wellcome“ }, ()=>{
[Link]([Link])})

forceUpdate() - By default, the render() function will be called when props or state change. But if some UI components use
some other data than the state or prop that needs to change, we need to notify React to redraw everything by calling the
forceUpdate() function.
Notes when using React-Native

 Data that needs to be printed on the screen and needs to change the UI when it changes is put into the state.
 Data that does not need to change the UI when it changes can use [Link] so that this variable can perform
the = (assignment) operation and be used directly like normal variables.
 Data in prop should not change.
 The state should only contain data, should not contain Views / Components in the state. Doing so can cause
21

double data and UI management becomes more complicated and difficult to customize later.
VIEW DESIGN IN REACT NATIVE
• Ex 2

export class StyleDemo extends [Link] {


render() { return (
<View>
<Text style={[Link]}>just red</Text>
<Text style={[Link]}>just bigblue</Text>
<Text style={[[Link], [Link]]}>bigblue, then red</Text>
<Text style={[[Link], [Link]]}>red, then bigblue</Text>
</View>
); }}
const styles = [Link]({
bigblue: {
color: 'blue',
fontWeight: 'bold', 22

fontSize: 30,
}, red: { color: 'red’, }, });
VIEW DESIGN IN REACT NATIVE
• Using CSS
• Should be used CSS in another file for manage easier

23
COMMONLY USED COMPONENTS OF REACT NATIVE
• Ex 3 (from page 20 to 27)
import React from 'react';
import { Image, View, Text, Button, TouchableOpacity, FlatList, StyleSheet } from 'react-native';
import { Colors } from '../../../configs/style';
export class Components extends [Link] {
static navigationOptions = ({ navigation }) => {
return {
title: "COMPONENT",
headerStyle: {
backgroundColor: [Link]
},
headerTintColor: [Link],
headerTitleStyle: {
alignSelf: 'center'
} }; }; 24
COMMONLY USED COMPONENTS OF REACT NATIVE
constructor(props) { super(props);
[Link] = { message: "Message 2",
listData: [ {
image: require('../../../assets/images/[Link]'),
title: "IOS“ }, {
image: require('../../../assets/images/[Link]'),
title: "Android"
}, {
image: require('../../../assets/images/[Link]'),
title: "React Native"
}
] }
[Link] = 0;
[Link] = 0; }
onPressButtonDemo() {
[Link]++; 25

[Link]({ message: "Clicked Button: " + [Link] }) }


COMMONLY USED COMPONENTS OF REACT NATIVE
onPressTouchableOpacityDemo() {

[Link]++;

[Link]({ message: "Clicked TouchableOpacity: " + [Link] }) }

render() {

return (

<View style={[Link]}>

{/* show 1 message to screen */}

<Text style={[Link]}>WELCOME TO TEXT OF REACT-NATIVE</Text>

<View style={[Link]}>

{/* show pictures from local resource */}

<Image

style={[Link]} /* Image Style */

resizeMode={'contain'} /* properties of image show (center, contain, cover, repeat, stretch ) */ 26

source={require('../../../assets/images/[Link]')}

/>
COMMONLY USED COMPONENTS OF REACT NATIVE
{/* show images from other web/server */}
<Image
style={[Link]}
resizeMode={'contain'}
source={{ uri: '[Link] }}
/>
</View>
{/* print one value of state on screen */}
<Text style={[Link]}>{[Link]}</Text>
{/* using Button with với press function */}
<Button
onPress={() => [Link]()}
title="Click Me!“
color = “#841584”
27
/>
COMMONLY USED COMPONENTS OF REACT NATIVE
{/* usingTouchableOpacity with press similar to button */}
<TouchableOpacity
style={[Link]}
onPress={() => [Link]()}>
<Text style={[Link]}>Touchable Opacity</Text>
</TouchableOpacity>
{/* Sử dụng FlatList để hiển thị ra một danh sách */}
<FlatList
data={[Link]}
renderItem={({ item }) => [Link](item)}
keyExtractor={(item, index) => [Link]()}
/>
</View>
28
); }
COMMONLY USED COMPONENTS OF REACT NATIVE
/* show in detail 1 item */
renderItem(item) {
return (
<View style={[Link]}>
<Image
style={[Link]}
resizeMode={'contain'}
source={[Link]}
/>
<Text>{[Link]}</Text>
</View>
) }}
const Styles = [Link]({
container: {
29
flex: 1,
flexDirection: 'column',
alignItems: 'center',
COMMONLY USED COMPONENTS OF REACT NATIVE
//Style [Link]
textMessage: {
marginTop: 16,
color: 'green',
fontSize: 16,
},
imgLogo: {
width: 50,
height: 50,
margin: 4
},
30
COMMONLY USED COMPONENTS OF REACT NATIVE
btnStyle: {
height: 50,
width: 200,
borderColor: [Link],
borderRadius: 5,
borderWidth: 2,
justifyContent: "center",
alignItems: 'center',
margin: 8

}, textAction: {
color: [Link],
fontSize: 20,
fontWeight: 'bold'

}, containerItem: {
marginTop: 16,
31
flexDirection: 'row',
alignItems: 'center’ } });
COMMONLY USED COMPONENTS OF REACT NATIVE

32
COMMONLY USED COMPONENTS OF REACT NATIVE
Component “VIEW”
• Divide child views vertically or horizontally based on the flexDirection attribute in the
style as 'column/row' (vertical/horizontal),
• or used to contain many child views or when needing to print a view that does not
display anything on the screen, for example:
{ (Condition) ? <Text> Text Message <Text> : <View/> }
Component “Text”
Used to display a message on the screen. Can use fixed text or print the contents of a
variable on the screen
<Text>Message Here<Text>
<Text>{variable_here}<Text> 33
COMMONLY USED COMPONENTS OF REACT NATIVE
Component “Image”
To show image to screen. There are 3 methods
- Show image from local
<Image source={require('/react-native/img/[Link]’)} />
- Show image from URL
<Image style={{width: 50, height: 50}}
source={{uri: '[Link] />
- Show image base 64
<Image style={{width: 66, height: 58}} source={{uri:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqA
AAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAAYGBgYGBgYGBgbmQw+P/eMrC
5UTVAAAAABJRU5ErkJggg==‘}} />
34
COMMONLY USED COMPONENTS OF REACT NATIVE
Resize Mode familiar:
cover: (default) The image will keep the same ratio. The image will be larger
than or equal to the container.
contain: The image will keep the same ratio. The image will be smaller than
or equal to the container.
center: Center the image in both directions. Take the middle part, similar to
cover.
repeat: Repeat the image to cover the entire size of the container.
stretch: Change the image ratio to stretch to the same size as the container.
35
COMMONLY USED COMPONENTS OF REACT NATIVE
Component “Button”
Ex:
onPressButtonDemo(){
[Link]("Click Button")
}
....
<Button
onPress={() => [Link]()}
title="Click Me!"
color="#841584"
/> 36
COMMONLY USED COMPONENTS OF REACT NATIVE
Component “TouchableOpacity”
Using to replace Button component for style is similar to android & iOS and
can including sub view
Ex
<TouchableOpacity
style={[Link]}
onPress={() => [Link]()}>
<Text style={[Link]}>Click Me</Text>
</TouchableOpacity> 37
COMMONLY USED COMPONENTS OF REACT NATIVE
Component “FlatList”
To show list on screen

<FlatList

data={[Link]}

renderItem={({ item }) => [Link](item)}

keyExtractor={(item, index) => [Link]()} />

/* show 1 item on screen */

renderItem(item) {

return (

<View style={[Link]}>

<Image

style={[Link]}

resizeMode={'contain'}
38
source={[Link]} />

<Text>{[Link]}</Text>

</View> )}
COMMONLY USED COMPONENTS OF REACT NATIVE
• Note when using FlatList
When a data component (eg data[0] = ...) of yours changes, it usually doesn't
re-fresh the UI, so you'll need to add an attribute extraData={[Link]}. Now,
every time the state changes, the list is re-fresh.
You can use Flatlist to do like GridView in android based on the attribute
numColumns={colum} (colum is the number of columns). But you'll need to
calculate the width, height of each column to display it best (Not available like
fill_parent in android).

39
PROP AND DATA PASS BETWEEN THE VIEWS
Example – create 2 File: [Link] & [Link] on the same folder
import React from 'react';

import { View, Text, FlatList, StyleSheet } from 'react-native';

import { Colors } from '../../../configs/style';

import { ViewItem } from './ViewItem'

export class App extends [Link] {

//Header ứng dụng (tùy chọn)

static navigationOptions = ({ navigation }) => {

return {

title: "PROPS",

headerStyle: { backgroundColor: [Link] },

headerTintColor: [Link],

headerTitleStyle: { alignSelf: 'center’ } }; };

constructor(props) {

super(props); [Link] = { message: "",

listData: [

{ image: require('../../../assets/images/[Link]'),

title: "IOS" 40

}, { image: require('../../../assets/images/[Link]’), title: "Android“ }, {

image: require('../../../assets/images/[Link]'),
PROP AND DATA PASS BETWEEN THE VIEWS
// onPressItem

onPressItem(item, index) { [Link]({ message: "Click item: " + index + " - title: " + [Link] }) }

render() {

return (

<View style={[Link]}>

<Text style={[Link]}>{[Link]}</Text>

<FlatList

style={[Link]}

data={[Link]}

renderItem={({ item, index }) => [Link](item, index)}

keyExtractor={(item, index) => [Link]()}

/> </View> ); }

/* Show 1 item */

renderItem(item, index) {

return (

<ViewItem

data={item} //Truyền item này qua ViewItem như một prop

onPressItem={(itemPress) => { [Link](itemPress, index) }} // truyền một hàm qua để bắt sự kiện click item
41
/> ) }}

const Styles = [Link]({

container: { flex: 1, flexDirection: 'column’, alignItems: 'center’, backgroundColor: [Link],


PROP AND DATA PASS BETWEEN THE VIEWS
Ex: [Link]
import React from 'react';
import { Image, View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { Colors } from '../../../configs/style';
export class ViewItem extends [Link] {
constructor(props) {
super(props);
[Link] = {
color: [Link]
} }
onPressItem() {
//can adding event handle, Ex change color of item
let newColor = [Link];
if ([Link] == [Link]) {
newColor = [Link]
} 42

[Link]({ color: newColor })


//or can pass data out site in order to other function process
PROP AND DATA PASS BETWEEN THE VIEWS
render() {

//in props được truyền qua để kiểm tra

[Link]([Link])

//render to screen item is passed through props

return (

<TouchableOpacity style={[[Link], { backgroundColor: [Link] }]} onPress={() => [Link]()}>

<Image

style={[Link]}

resizeMode={'contain'}

source={[Link]} //using prop is passed through

/>

<Text>{[Link]}</Text>

</TouchableOpacity>

) }}
43
const Styles = [Link]({

imgLogo: { width: 50, height: 50, margin: 4 },

containerItem: { marginLeft: 16, marginRight: 16, marginTop: 16, flexDirection: 'row', alignItems: 'center' }
PROP AND DATA PASS BETWEEN THE VIEWS
• Sender(viewitem is 1 customized component)

<ViewItem
data={item} //pass this item by ViewItem as 1 prop
onPressItem={(itemPress) => { [Link](itemPress, index) }}
// pass function to event handle click item />
• Receiver
The data receiver can use the data passed through props. (It throws some data
over and the receiver can access it through props)
44
PROP AND DATA PASS BETWEEN THE VIEWS
...
render() {
//in props được truyền qua để kiểm tra
[Link]([Link])
//render ra màn hình item được truyền vào thông qua props
return (
<TouchableOpacity style={[[Link], { backgroundColor: [Link] }]} onPress={() => [Link]()}>
<Image
style={[Link]}
resizeMode={'contain'}
source={[Link]} // //using prop is passed through
/>
<Text>{[Link]}</Text>
</TouchableOpacity>
) 45

}
PROP AND DATA PASS BETWEEN THE VIEWS
Passing data coming back is also demonstrated in the example through handling the onPressItem(
onPressItem() {
//Bạn có thể xử lý sự kiện ở đây nếu cần, ví dụ như như đổi màu item
let newColor = [Link];
if ([Link] == [Link]) {
newColor = [Link]
}
[Link]({
color: newColor
})
// can pass data out site in order to other function process
[Link]([Link])
46
}
PROP AND DATA PASS BETWEEN THE VIEWS
• Note:
Do not change the data in props on the receiving side.
Each component should be separated into its own component and
communicate with the main component via props to minimize the need to
redraw the entire component, especially components that contain timers
(setInterval(), setTimeOut()...).

47
USING LIBRARY IN REACT NATIVE
Installing libraries
Usually in React-Native, libraries are used a lot, perhaps for a few reasons:
- Code from scratch takes longer.
- Libraries are built by many people, so the ability is better than coding alone.
There is community support, so if there are errors, it is easy to fix them.
Libraries related to SDKs of developers such as Facebook, Google, Firebase...
are all developed by the community to support you in building the best
application.
- And many other reasons.
48
npm install pakage_name
CHANGE PASS AND THROUGH BETWEEN SCREENS
• Can be used react-navigation library (v.2.18.1) to switch between screens. You
can learn more about this library at ([Link]
• Install the library: Go to the project you created and run the following
command to install the library npm install --save react-navigation
• Use the library:
• - Build the application structure: To better understand the following demo,
please review the [Link] file in Example (Example/app/[Link]). Below is
the part of creating the application's skeleton structure based on
StackNavigator of the react-navigation library.
49
SWITCHING BETWEEN SCREENS
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import { StyleSheet, View } from 'react-native’;

// import toàn bộ các class Screen từ modules/screens (những class được xuất thông qua file modules/screens/[Link])
import * as Screens from './modules/screens';

//Tạo StackNavigator từ thư viện react-navigation


const AppNavigator = StackNavigator({
HOME: {
screen: [Link]
},
STYLES: {
screen: [Link]
}, 50
SWITCHING BETWEEN SCREENS
COMPONENT: {

screen: [Link]

},

PROPS: {

screen: [Link]

} }, {

headerMode: "screen"

});

export default class App extends Component {

render() {

return (

<View style={[Link]}>

{/*Vẽ stack ứng dụng ra màn hình*/}

<AppNavigator /> 51

</View> ); }}

const styles = [Link]({


SWITCHING BETWEEN SCREENS
We declare an application with 4 screens: HOME, STYLES, COMPONENT,
PROPS. By default, the screen at the top will appear first. The content of each
screen is as follows:
HOME: {
screen: [Link]
}
where [Link] is a class imported from the screens module.
Note the command line:
IMPORT * AS SCREENS FROM './MODULES/SCREENS’ 52
SWITCHING BETWEEN SCREENS
This command line imports all the classes exported through the [Link] file. So if you
add a new screen, note the [Link] file to export the class you just created.
Switch screen: there are 2 ways to switch screens:
• Switch and delete all previous screens:
// chuyển qua màn hình PROPS đã khai báo trong App StackNavigator
let pageContinue = [Link]({
index: 0,
actions: [[Link]({ routeName: "PROPS", params: {} })]
});
[Link](pageContinue); 53
SWITCHING BETWEEN SCREENS
params: {} - This is where you pass data to the next screen. You can pass an object to
the next screen using this syntax.
• Switch and retain the previous screen to return
// switching PROPS is declared in App StackNavigator
[Link]("PROPS");
//or
[Link]("PROPS", {});
{} - This is also how you pass an object to the next screen.
By default, if you display the Status bar, there will be a back button, but if necessary,
you can return by calling the following function:
[Link](); 54
SWITCHING BETWEEN SCREENS
• Show status bar
static navigationOptions = ({ navigation }) => {
return {
title: "PROPS",
headerStyle: {
backgroundColor: [Link]
},
headerTintColor: [Link],
headerTitleStyle: {
alignSelf: 'center'
}
};
55
};
COMMUNICATION BETWEEN CLIENT & SERVER
• RESTful API – common used to link between Client and Server

56
COMMUNICATION BETWEEN CLIENT & SERVER
This Demo is presented quite clearly and in detail
in the Example (app/modules/screens/RestFul/[Link]).
You should run the example first to see how it works.
The demo consists of calling a public api from
[Link] (GET)
and displaying the result as follows:

57
COMMUNICATION BETWEEN CLIENT & SERVER
import { getBaseURL } from '../configs/config';
let networkError = {
error_code: -1,
message: 'Network error',
data: {}
};
export class RESTFulAPI {
//Định nghĩa một api lấy language từ server.
// Public api có sẵn tại [Link]
getLanguage() {
let api = getBaseURL() + "get_languages";
58

return [Link](api);
}
COMMUNICATION BETWEEN CLIENT & SERVER
//define 1 asynchronous method to support methods, GET, POST, PUT, DELETE (GET deafault)

async fetchData(api, method = 'GET', body) {

let headers = {

Accept: 'application/json',

'Content-Type': 'application/json',

};

try {

let response = await fetch(api, {

method: method,

headers: headers,

body: [Link](body)

});

let responseJson = await [Link]();

return responseJson;

} catch (error) {
59
return networkError;

} }}

export default RESTClient = new RESTFulAPI();


COMMONLY USED COMPONENTS OF REACT NATIVE
• Here I define a class to manage the exchange and communication between the client
and the server. The fetchData() function is an asynchronous function that supports
calling RESTful methods.
• And this is how we call the fetchData() function and clearly define an access api to
get the language list. Note: Instead of directly placing the link
[Link] I call the getBaseURL() function so that if I
change the api later, I don't have to change many places, just go to config and
change and it's done.
getLanguage() {
let api = getBaseURL() + "get_languages";
return [Link](api);
} 60
COMMONLY USED COMPONENTS OF REACT NATIVE
• Example of calling fetchData() with POST method
let api = getBaseURL() + "get_languages";
let body = {...}
return [Link](api, 'POST', body);
// This is how to POST a body object to the system
// The POST method is not supported on this server so it probably won't work.

61
COMMONLY USED COMPONENTS OF REACT NATIVE
Using RESTClient
import RESTClient from '../../../libs/RESTClient';
...
getLanguagesFromServer() {
//call method to get language from RestClient class to get data
[Link]().then(
(result) => {
//asynchronous process and return results
if (result.error_code == 0) {
//check error and reset data to render data
[Link]({
listData: [Link]
})
}}
62
)}
STORE DATA IN REACT NATIVE
- React-Native supports storage by default via AsyncStorage provided by default in the react-native library
package. See the Storage section below to learn more about this storage method. In addition, I would like to
introduce the method of storing structured data using realm database.
- Realm is considered one of the best and most optimized database support libraries for programmers on current
mobile lines.
import { AsyncStorage } from "react-native";
Using library
// lưu trữ dữ liệu theo dạng key -> value (nếu value là một đối tượng thì nên chuyển đổi về JSON trước sử
dụng [Link](obj))
[Link]("language", "vi");
//Đọc giá trị lên và sử dụng.
[Link]("language").then(result => {
[Link](result) //in ra màn hình console: vi 63

})
STORE DATA IN REACT NATIVE
• Database
Using realm to store data in database

64

You might also like