FirstProject App Installation Guide
FirstProject App Installation Guide
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
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)
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
constructor(props) {
super(props);
[Link] = {
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';
constructor(props) {
super(props);
render() {
}}
constructor(props) {
super(props);
[Link] = {
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
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]++;
render() {
return (
<View style={[Link]}>
<View style={[Link]}>
<Image
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) {
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';
return {
title: "PROPS",
headerTintColor: [Link],
constructor(props) {
listData: [
{ image: require('../../../assets/images/[Link]'),
title: "IOS" 40
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]}
/> </View> ); }
/* Show 1 item */
renderItem(item, index) {
return (
<ViewItem
onPressItem={(itemPress) => { [Link](itemPress, index) }} // truyền một hàm qua để bắt sự kiện click item
41
/> ) }}
[Link]([Link])
return (
<Image
style={[Link]}
resizeMode={'contain'}
/>
<Text>{[Link]}</Text>
</TouchableOpacity>
) }}
43
const Styles = [Link]({
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';
screen: [Link]
},
PROPS: {
screen: [Link]
} }, {
headerMode: "screen"
});
render() {
return (
<View style={[Link]}>
<AppNavigator /> 51
</View> ); }}
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)
let headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
try {
method: method,
headers: headers,
body: [Link](body)
});
return responseJson;
} catch (error) {
59
return networkError;
} }}
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