Learn React Native: A Comprehensive Guide
Learn React Native: A Comprehensive Guide
i
React Native
Audience
This tutorial is designed for JavaScript and React developers who aspire to learn mobile
building skills. By following this course, you will expand your React and JavaScript
knowledge, learn some concepts of functional programming, and prepare to enter the
mobile world.
Since JavaScript world is moving forward, we will keep up with it and use EC6 syntax in
this tutorial.
Prerequisites
To be able to follow this tutorial, you should be familiar with React and have solid
JavaScript knowledge. Even if you do not have previous experience with React, you should
be able to follow it. In this tutorial, we will explain some fundamental React concepts.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@[Link]
i
React Native
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
ii
React Native
iii
React Native
Core Concepts
1
1. React Native – Overview React Native
For better understanding of React Native concepts, we will borrow a few lines from the
official documentation –
React Native lets you build mobile apps using only JavaScript. It uses the same design as
React, letting you compose a rich mobile UI from declarative components.
With React Native, you don't build a mobile web app, an HTML5 app, or a hybrid app; you
build a real mobile app that's indistinguishable from an app built using Objective-C or Java.
React Native uses the same fundamental UI building blocks as regular iOS and Android
apps. You just put those building blocks together using JavaScript and React.
Code sharing − You can share most of your code on different platforms.
Community – The community around React and React Native is large, and you
will be able to find any answer you need.
2
2. React Native – Environment Setup React Native
There are a couple of things you need to install to set up the environment for React Native.
We will use OSX as our building platform.
3
React Native
cd reactTutorialApp
react-native start
You should keep this terminal window running while developing your app.
react-native run-ios
4
3. React Native – State React Native
The data inside React Components is managed by state and props. In this chapter, we
will talk about state.
Using State
This is our root component. We are just importing Home which will be used in most of the
chapters.
NOTE: This file won't change during the course of this tutorial, so we will leave it out in
the future.
[Link]
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import Home from './src/components/home/[Link]'
Initial state is defined inside the Home class by using the state = {} syntax.
5
React Native
src/components/home/[Link]
import React, { Component } from 'react';
import { Text, View } from 'react-native';
render() {
return (
<View>
<Text>
{[Link]}
</Text>
</View>
);
}
}
6
React Native
We can see in emulator text from the state as in the following screenshot.
Updating State
Since state is mutable, we can update it by creating the deleteState function and call it
using the onPress = {[Link]} event.
src/components/home/[Link]
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
7
React Native
render() {
return (
<View>
<Text onPress = {[Link]}>
{[Link]}
</Text>
</View>
);
}
}
export default Home;
NOTES − In all chapters, we will use the class syntax for stateful (container) components
and function syntax for stateless (presentational) components. We will learn more about
components in the next chapter.
In our second example, we are using the arrow function syntax for updateState. You
should keep in mind that this syntax uses the lexical scope, and this keyword will be
bound to the environment object (Class). This will sometimes lead to unexpected behavior.
The other way to define methods is to use the EC5 functions but in that case we will need
to bind this manually in the constructor. Consider the following example to understand
this.
constructor(){
super()
[Link] = [Link](this)
}
updateState(){
8
React Native
//
}
render(){
//
}
}
9
4. React Native – Props React Native
In our last chapter, we showed you how to use mutable state. In this chapter, we will
show you how to combine the state and the props.
Presentational components should get all data by passing props. Only container
components should have state.
Container Component
We will now understand what a container compenent is and also how it works.
Theory
Now we will update our container component. This component will handle the state and
pass the props to the presentational component.
Container component is only used for handling state. All functionality related to view
(styling etc.) will be handled in the presentational component.
Example
If we want to use example from the last chapter we need to remove the Text element
from the render function since this element is used for presenting text to the users. This
should be inside the presentational component.
Let us review the code in the example given below. We will import the
PresentationalComponent and pass it to the render function.
src/components/home/[Link]
import React, { Component } from 'react'
import { View } from 'react-native'
import PresentationalComponent from './PresentationalComponent'
state = {
myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
10
React Native
updateState = () ⇒ {
[Link]({ myState: 'The state is updated' })
}
render() {
return (
<View>
<PresentationalComponent myState = {[Link]} updateState
= {[Link]}/>
</View>
)
}
}
Presentational Component
We will now understand what a presentational component is and also how it works.
Theory
Presentational components should be used only for presenting view to the users. These
components do not have state. They receive all data and functions as props.
Example
As we mentioned in our previous chapter, we are using the EC6 function syntax for
presentational components.
Our component will receive props, return view elements, present text using
{[Link]} and call the {[Link]} function when a user clicks on the
text.
11
React Native
src/components/home/[Link]
import React, { Component } from 'react'
import { Text, View } from 'react-native'
Now, we have the same functionality as in our State chapter. The only difference is that
we refactored our code to the container and the presentational component.
You can run the app and see the text as in the following screenshot.
12
5. React Native – Styling React Native
You can use the style property to add the styles inline. However, this is not the best
practice because it can be hard to read the code.
Container Component
In this section, we will simplify our container component from our previous chapter.
src/components/home/[Link]
import React, { Component } from 'react'
import { View } from 'react-native'
import PresentationalComponent from './PresentationalComponent'
render() {
return (
<View>
<PresentationalComponent myState = {[Link]}/>
</View>
)
}
}
export default Home
Presentational Component
In the following example, we will import the StyleSheet. At the bottom of the file, we will
create our stylesheet and assign it to the styles constant. Note that our styles are in
camelCase and we do not use px or % for styling.
To apply styles to our text, we need to add style = {[Link]} property to the
Text element.
13
React Native
src/components/home/[Link]
import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'
14
React Native
15
6. React Native – Flexbox React Native
We will use the same code that we used in our React Native - Styling chapter. We will
only change the PresentationalComponent.
Layout
To achieve the desired layout, flexbox offers three main properties − flexDirection
justifyContent and alignItems.
'center', 'flex-start',
'flex-end', 'space- Used to determine how should elements be
justifyContent
around', 'space- distributed inside the container.
between'
If you want to align the items vertically and centralize them, then you can use the following
code.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'
16
React Native
redbox: {
width: 100,
height: 100,
backgroundColor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundColor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundColor: 'black'
},
})
17
React Native
If the items need to be moved to the right side and spaces need to be added between
them, then we can use the following code.
src/components/home/[Link]
import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'
18
React Native
redbox: {
width: 100,
height: 100,
backgroundColor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundColor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundColor: 'black'
},
})
19
React Native
The following example shows how you can style black and yellow boxes using flexbox.
Each container uses different properties.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, Image, StyleSheet } from 'react-native'
const Home = () ⇒ {
return (
<View>
<View style = {style.container1}>
<View style = {[Link]}/>
<View style = {[Link]}/>
</View>
20
React Native
)
}
container2: {
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
21
React Native
borderBottomWidth: 1,
borderBottomColor: '#f4c842'
},
container3: {
flexDirection: 'row',
justifyContent: 'flex-end',
borderBottomWidth: 1,
borderBottomColor: '#f4c842'
},
container4: {
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: '#f4c842'
},
container5: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
blackImg: {
backgroundColor: 'black',
height: 90,
width: 90
},
yellowImg: {
backgroundColor: 'yellow',
height: 50,
width: 50
}
})
22
React Native
23
7. React Native – ListView React Native
In this chapter, we will show you how to create a list in React Native. We will import List
in our Home component and show it on screen.
src/components/home/[Link]
import React from 'react'
import List from './[Link]'
To create a list, we will use the map() method. This will iterate over an array of items,
and render each one.
src/components/home/[Link]
import React, { Component } from 'react'
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native'
24
React Native
name: 'Robert',
},
{
id: 3,
name: 'Mary',
}
]
}
render() {
return (
<View>
{
[Link]((item, index) => (
<TouchableOpacity
key = {[Link]}
style = {[Link]}
onPress = {() => [Link](item)}
>
<Text style={[Link]}>
{[Link]}
</Text>
</TouchableOpacity>
))
}
</View>
)
}
}
25
React Native
26
React Native
You can click on each item in the list to trigger an alert with the name.
27
8. React Native – Text Input React Native
In this chapter, we will show you how to work with TextInput elements in React Native.
src/components/home/[Link]
import React from 'react';
import Inputs from './[Link]'
const Home = () ⇒ {
return (
<Inputs />
)
}
Inputs
We will define the initial state. After defining the initial state, we will create the
handleEmail and the handlePassword functions. These functions are used for updating
state.
The login() function will just alert the current value of the state.
We will also add some other properties to text inputs to disable auto capitalisation, remove
the bottom border on Android devices and set a placeholder.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-
native'
state = {
email: '',
password: ''
}
28
React Native
handleEmail = (text) ⇒ {
[Link]({ email: text })
}
handlePassword = (text) ⇒ {
[Link]({ password: text })
}
render(){
return (
<View style = {[Link]}>
<TextInput style = {[Link]}
underlineColorAndroid = "transparent"
placeholder = "Email"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText = {[Link]}/>
<TouchableOpacity
style = {[Link]}
onPress = { () ⇒ [Link]([Link],
[Link])}>
<Text style = {[Link]}>
Submit
29
React Native
</Text>
</TouchableOpacity>
</View>
)
}
}
input: {
margin: 15,
height: 40,
borderColor: '#7a42f4',
borderWidth: 1
},
submitButton: {
backgroundColor: '#7a42f4',
padding: 10,
margin: 15,
height: 40,
},
submitButtonText:{
color: 'white'
}
})
30
React Native
Whenever we type in one of the input fields, the state will be updated. When we click on
the Submit button, text from inputs will be shown inside the dialog box.
31
9. React Native – ScrollView React Native
In this chapter, we will show you how to work with the ScrollView element.
src/components/home/[Link]
import React from 'react'
import ScrollViewExample from './[Link]'
const Home = () ⇒ {
return (
<ScrollViewExample />
)
}
src/components/home/[Link]
import React, { Component } from 'react';
import { Text, Image, View, StyleSheet, ScrollView } from 'react-native';
32
React Native
render() {
return (
<View>
<ScrollView>
{
[Link]((item, index) ⇒ (
<View key = {[Link]} style = {[Link]}>
<Text>{[Link]}</Text>
</View>
))
}
</ScrollView>
</View>
)
}
}
export default ScrollViewExample
const styles = [Link] ({
item: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 30,
margin: 2,
borderColor: '#2a4944',
borderWidth: 1,
backgroundColor: '#d2f7f1'
}
})
33
React Native
When we run the app, we will see the scrollable list of names.
34
10. React Native – Images React Native
In this chapter, we will understand how to work with images in React Native.
Adding Image
Let us create a new folder img inside the src folder. We will add our image
([Link]) inside this folder.
src/components/home/[Link]
import React from 'react';
import ImagesExample from './[Link]'
const Home = () ⇒ {
return (
<ImagesExample />
)
}
src/components/home/[Link]
import React, { Component } from 'react'
import { Image } from 'react-native'
const Home = () ⇒ (
<Image source = {require('../../img/[Link]')} />
)
35
React Native
Screen Density
React Native offers a way to optimize images for different devices using @2x, @3x suffix.
The app will load only the image necessary for particular screen density.
The following will be the names of the image inside the img folder.
my-image@[Link]
my-image@[Link]
36
React Native
Network Images
When using network images, instead of require, we need the source property. It is
recommended to define the width and the height for network images.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, Image } from 'react-native'
const Home = () ⇒ (
<Image
source = {{ uri:
'[Link] }}
style = {{ width: 200, height: 200 }}
/>
)
export default Home
37
11. React Native – HTTP React Native
In this chapter, we will show you how to use fetch for handling network requests.
src/components/home/[Link]
import React from 'react';
import HttpExample from './[Link]'
const Home = () ⇒ {
return (
<HttpExample />
)
}
Using Fetch
We will use the componentDidMount lifecycle method to load the data from server as
soon as the component is mounted. This function will send GET request to the server,
return JSON data, log output to console and update our state.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, Text } from 'react-native'
state = {
data: ''
}
componentDidMount = () ⇒ {
fetch('[Link] {
method: 'GET'
})
38
React Native
.then((response) ⇒ [Link]())
.then((responseJson) ⇒ {
[Link](responseJson);
[Link]({
data: responseJson
})
})
.catch((error) ⇒ {
[Link](error);
});
}
render() {
return (
<View>
<Text>
{[Link]}
</Text>
</View>
)
}
}
39
React Native
40
12. React Native – Buttons React Native
In this chapter, we will show you touchable components in react Native. We call them
'touchable' because they offer built in animations and we can use the onPress prop for
handling touch event.
Facebook offers the Button component, which can be used as a generic button. Consider
the following example to understand the same.
src/components/home/[Link]
import React, { Component } from 'react'
import { Button } from 'react-native'
const Home = () ⇒ {
const handlePress = () ⇒ false
return (
<Button
onPress = {handlePress}
title = "Red button!"
color = "red"
/>
)
}
export default Home
If the default Button component does not suit your needs, you can use one of the following
components instead.
Touchable Opacity
This element will change the opacity of an element when touched.
src/components/home/[Link]
import React from 'react'
import { TouchableOpacity, StyleSheet, View, Text } from 'react-native'
const Home = () ⇒ {
return (
<View style = {[Link]}>
41
React Native
<TouchableOpacity>
<Text style = {[Link]}>
Button
</Text>
</TouchableOpacity>
</View>
)
}
text: {
borderWidth: 1,
padding: 25,
borderColor: 'black',
backgroundColor: 'red'
}
})
Touchable Highlight
When a user presses the element, it will get darker and the underlying color will show
through.
src/components/home/[Link]
import React from 'react'
import { View, TouchableHighlight, Text, StyleSheet } from 'react-native'
42
React Native
<TouchableHighlight>
Button
</Text>
</TouchableHighlight>
</View>
)
}
text: {
borderWidth: 1,
padding: 25,
borderColor: 'black',
backgroundColor: 'red'
}
})
src/components/home/[Link]
import React from 'react'
import { View, TouchableNativeFeedback, Text, StyleSheet } from 'react-native'
43
React Native
Button
</Text>
</TouchableNativeFeedback>
</View>
)
}
text: {
borderWidth: 1,
padding: 25,
borderColor: 'black',
backgroundColor: 'red'
}
})
<TouchableWithoutFeedback>
<Text>
Button
</Text>
</TouchableWithoutFeedback>
44
13. React Native – Animations React Native
In this chapter, we will show you how to use LayoutAnimation in React Native.
Home Component
We will use Home screen like in other chapters. Let us now import the Animations
component and render it on screen.
src/components/home/[Link]
import React from 'react';
import Animations from './[Link]'
const Home = () ⇒ {
return (
<Animations />
)
}
Animations Component
We will set myStyle as a property of the state. This property is used for styling an element
inside PresentationalAnimationComponent.
src/components/home/Home
import React, { Component } from 'react'
import { View, LayoutAnimation, TouchableOpacity, Text, StyleSheet } from
'react-native'
45
React Native
state = {
myStyle: {
height: 100,
backgroundColor: 'red'
}
}
expandElement = () ⇒ {
[Link]([Link]);
[Link]({
myStyle: {
height: 400,
backgroundColor: 'red'
}
})
}
collapseElement = () ⇒ {
[Link]([Link]);
[Link]({
myStyle: {
height: 100,
backgroundColor: 'red'
}
})
}
render() {
return (
<View>
<View>
<View style = {[Link]}>
</View>
<TouchableOpacity>
46
React Native
<TouchableOpacity>
<Text style = {[Link]} onPress = {[Link]}>
Collapse
</Text>
</TouchableOpacity>
</View>
)
}
}
47
React Native
You can test the app and see the animations we created. The initial setup will look like this –
48
React Native
Example
In this example, we will dynamically change the width and the height of the box. Since
the Home component will be the same, we will only change the Animations component.
src/components/home/Animations
import React, { Component } from 'react'
import { View, StyleSheet, Animated, TouchableOpacity } from 'react-native'
49
React Native
animatedBox = () ⇒ {
[Link]([Link], {
toValue: 200,
duration: 1000
}).start()
[Link]([Link], {
toValue: 500,
duration: 500
}).start()
}
render() {
const animatedStyle = { width: [Link], height:
[Link] }
return (
<TouchableOpacity style = {[Link]} onPress =
{[Link]}>
<[Link] style = {[[Link], animatedStyle]}/>
</TouchableOpacity>
)
}
}
export default Animations
const styles = [Link]({
container: {
justifyContent: 'center',
alignItems: 'center'
},
box: {
backgroundColor: 'blue',
width: 50,
height: 100
}
})
50
React Native
51
React Native
52
14. React Native – Debugging React Native
React native offers a couple of methods that help in debugging your code.
53
React Native
Reload − Used for reloading simulator. You can use shortcut command + R
Enable Live Reload − Used for enabling live reloading whenever your code is
saved. The debugger will open at localhost:8081/debugger-ui.
Start Systrace − Used for starting Android marker based profiling tool.
Show Inspector − Used for opening inspector where you can find info about your
components. You can use shortcut command + I
Show Perf Monitor − Perf monitor is used for keeping track of the performance
of your app.
54
15. React Native – Router React Native
Step 2
Since we want our router to handle the entire application, we will add it in [Link].
For Android, you can do the same in [Link].
55
React Native
src/components/routes/[Link]
import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Home from '../home/[Link]'
import About from '../about/[Link]'
const Routes = () ⇒ (
<Router>
<Scene key = "root">
<Scene key = "home" component = {Home} title = "Home" initial = {true} />
<Scene key = "about" component = {About} title = "About" />
</Scene>
</Router>
)
export default Routes
src/components/home/[Link]
import React from 'react'
import { TouchableOpacity, Text } from 'react-native';
import { Actions } from 'react-native-router-flux';
const Home = () ⇒ {
const goToAbout = () ⇒ {
[Link]()
}
return (
<TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
<Text>This is HOME!</Text>
</TouchableOpacity>
)
}
56
React Native
src/components/home/[Link]
import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import { Actions } from 'react-native-router-flux'
const About = () ⇒ {
const goToHome = () ⇒ {
[Link]()
}
return (
<TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
<Text>This is ABOUT</Text>
</TouchableOpacity>
)
}
export default About
57
React Native
You can press the button to switch to the about screen. The Back arrow will appear; you
can use it to get back to the previous screen.
58
React Native
59
16. React Native – Running IOS React Native
If you want to test your app in the IOS simulator, all you need is to open the root folder
of your app in terminal and run −
react-native run-ios
The above command will start the simulator and run the app.
After you open the app in simulator, you can press command + D on IOS to open the
developers menu. You can check more about this in our debugging chapter.
60
17. React Native – Running Android React Native
We can run the React Native app on Android platform by running the following code in the
terminal.
react-native run-android
Before you can run your app on Android device, you need to enable USB Debugging
inside the Developer Options.
When USB Debugging is enabled, you can plug in your device and run the code snippet
given above.
The Native Android emulator is slow. We recommend downloading Genymotion for testing
your app.
61
React Native
62
18. React Native – View React Native
View is the most common element in React Native. You can consider it as an equivalent of
the div element used in web development.
Use Cases
Let us now see a few common use cases.
When you need to wrap your elements inside the container, you can use View as
a container element.
When you want to nest more elements inside the parent element, both parent and
child can be View. It can have as many children as you want.
When you want to style different elements, you can place them inside View since
it supports style property, flexbox etc.
View also supports synthetic touch events, which can be useful for different
purposes.
We already used View in our previous chapters and we will use it in almost all subsequent
chapters as well. The View can be assumed as a default element in React Native. In
example given below, we will nest two Views and a text.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, Text } from 'react-native'
const Home = () ⇒ {
return (
<View>
<View>
<Text>This is my text</Text>
</View>
</View>
)
}
63
19. React Native – WebView React Native
In this chapter, we will learn how to use WebView. It is used when you want to render
web page to your mobile app inline.
Using WebView
The HomeContainer will be a container component.
src/components/home/[Link]
import React, { Component } from 'react'
import WebViewExample from './WebViewExample'
const Home = () ⇒ {
return (
<WebViewExample/>
)
}
src/components/home/[Link]
import React, { Component } from 'react'
import {
View,
WebView,
StyleSheet
} from 'react-native'
const WebViewExample = () ⇒ {
return (
<View style = {[Link]}>
<WebView
64
React Native
source = {{ uri:
'[Link]
nt' }}
/>
</View>
)
}
export default WebViewExample;
const styles = [Link]({
container: {
height: 350,
}
})
65
20. React Native – Modal React Native
In this chapter, we will show you how to use the modal component in React Native.
We will put logic inside ModalExample. We can update the initial state by running the
toggleModal.
After updating the initial state by running the toggleModal, we will set the visible
property to our modal. This prop will be updated when the state changes.
src/components/home/[Link]
import React from 'react'
import ModalExample from './[Link]'
const Home = () ⇒ {
return (
<ModalExample />
)
}
export default Home
src/components/home/[Link]
import React, { Component } from 'react';
import {
Modal,
Text,
TouchableHighlight,
View,
StyleSheet
} from 'react-native'
66
React Native
toggleModal(visible) {
[Link]({ modalVisible: visible });
}
render() {
return (
<View style = {[Link]}>
67
React Native
padding: 100
},
modal: {
flex: 1,
alignItems: 'center',
backgroundColor: '#f7021a',
padding: 100
},
text: {
color: '#3f2949',
marginTop: 10
}
})
68
React Native
69
21. React Native – ActivityIndicator React Native
In this chapter we will show you how to use the activity indicator in React Native.
Step 1 – Home
Home component will be used to import and show our ActivityIndicator.
src/components/home/[Link]
import React from 'react'
import ActivityIndicatorExample from './[Link]'
const Home = () ⇒ {
return (
<ActivityIndicatorExample />
)
}
Step 2 – ActivityIndicatorExample
Animating property is a Boolean which is used for showing the activity indicator. The latter
closes six seconds after the component is mounted. This is done using the
closeActivityIndicator() function.
src/components/home/[Link]
import React, { Component } from 'react';
import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet } from
'react-native';
70
React Native
componentDidMount = () ⇒ [Link]()
render() {
const animating = [Link]
return (
<View style = {[Link]}>
<ActivityIndicator
animating = {animating}
color = '#bc2b78'
size = "large"
style = {[Link]}
/>
</View>
)
}
}
activityIndicator: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 80
}
})
71
React Native
When we run the app, we will see the loader on screen. It will disappear after six seconds.
72
22. React Native – Picker React Native
In this chapter, we will create simple Picker with two available options.
src/components/home/[Link]
import React, { Component } from 'react'
import PickerExample from './[Link]'
const Home = () ⇒ {
return (
<PickerExample />
)
}
export default Home
Step 2 – Logic
[Link] is used for picker control.
src/components/home/[Link]
import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'
73
React Native
74
23. React Native – Status Bar React Native
In this chapter, we will show you how to control the status bar appearance in React Native.
The Status bar is easy to use and all you need to do is set properties to change it.
The hidden property can be used to hide the status bar. In our example it is set to false.
This is default value.
The barStyle can have three values – dark-content, light-content and default.
This component has several other properties that can be used. Some of them are Android
or IOS specific. You can check it in official documentation.
src/components/home/[Link]
import React, { Component } from 'react';
import { StatusBar } from 'react-native'
const Home = () ⇒ {
return (
<StatusBar barStyle = "dark-content" hidden = {false}/>
)
}
export default Home
If we run the app, the status bar will be visible and content will have dark color.
75
24. React Native – Switch React Native
Step 2 – Logic
We are passing value from the state and functions for toggling switch items to
SwitchExample component. Toggle functions will be used for updating the state.
src/component/home/[Link]
Example
import React, { Component } from 'react'
import {
View
} from 'react-native'
import SwitchExample from './SwitchExample'
constructor() {
super();
[Link] = {
switch1Value: false,
switch2Value: false,
}
}
toggleSwitch1 = (value) => {
[Link]({switch1Value: value})
[Link]('Switch 1 is: ' + value)
}
toggleSwitch2 = (value) => {
76
React Native
[Link]({switch2Value: value})
[Link]('Switch 2 is: ' + value)
}
render() {
return (
<View>
<SwitchExample
toggleSwitch1 = {this.toggleSwitch1}
toggleSwitch2 = {this.toggleSwitch2}
switch1Value = {[Link].switch1Value}
switch2Value = {[Link].switch2Value}/>
</View>
);
}
}
Step 3 – Presentation
Switch component takes two props. The onValueChange prop will trigger our toggle
functions after a user presses the switch. The value prop is bound to the state of the
HomeContainer component.
Example
import React, { Component } from 'react'
import {
View,
Switch,
StyleSheet
} from 'react-native'
77
React Native
<Switch
onValueChange = {props.toggleSwitch2}
value = {props.switch2Value}/>
</View>
)
}
If we press the switch, the state will be updated. You can check values in the console.
78
25. React Native – Text React Native
This component can be nested and it can inherit properties from parent to child. This can
be useful in many ways. We will show you example of capitalizing the first letter, styling
words or parts of the text, etc.
Step 2 – Home
In this step, we will just create a simple container.
src/components/home/[Link]
import React, { Component } from 'react'
import TextExample from './TextExample'
const Home = () ⇒ {
return (
<TextExample/>
)
}
export default Home
Step 3 – Text
In this step, we will use the inheritance pattern. [Link] will be applied to all Text
components.
You can also notice how we set other styling properties to some parts of the text. It is
important to know that all child elements have parent styles passed to them.
src/components/home/[Link]
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native'
const TextExample = () ⇒ {
return (
79
React Native
<Text>
orem ipsum dolor sit amet, sed do eiusmod.
</Text>
<Text>
Ut enim ad <Text style = {[Link]}>minim </Text>
veniam, quis aliquip ex ea commodo consequat.
</Text>
</Text>
</Text>
</View>
)
}
80
React Native
text: {
color: '#41cdf4',
},
capitalLetter: {
color: 'red',
fontSize: 20
},
wordBold: {
fontWeight: 'bold',
color: 'black'
},
italicText: {
color: '#37859b',
fontStyle: 'italic'
},
textShadow: {
textShadowColor: 'red',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius : 5
}
})
81
React Native
82
26. React Native – Alert React Native
Step 1 – Home
src/components/home/[Link]
import React from 'react'
import AlertExample from './[Link]'
const Home = () ⇒ {
return (
<AlertExample />
)
}
export default Home
Step 2 – [Link]
We will create a button for triggering the showAlert function.
src/components/home/[Link]
import React from 'react'
import { Alert, Text, TouchableOpacity, StyleSheet } from 'react-native'
const AlertExample = () ⇒ {
const showAlert = () ⇒ {
[Link](
'You need to...'
)
}
return (
<TouchableOpacity onPress = {showAlert} style = {[Link]}>
<Text>Alert</Text>
83
React Native
</TouchableOpacity>
)
}
export default AlertExample
const styles = [Link] ({
button: {
backgroundColor: '#4ba37b',
width: 100,
borderRadius: 50,
alignItems: 'center',
marginTop: 100
}
})
When you click the button, you will see the following –
84
27. React Native – Geolocation React Native
Step 1 – Home
src/components/home/[Link]
import React from 'react'
import GeolocationExample from './[Link]'
const Home = () ⇒ {
return (
<GeolocationExample />
)
}
Step 2 – Geolocation
We will start by setting up the initial state for that will hold the initial and the last position.
Now, we need to get current position of the device when a component is mounted using
the [Link]. We will stringify the response so we
can update the state.
src/components/home/[Link]
import React, { Component } from 'react'
import { View, Text, Switch, StyleSheet} from 'react-native'
85
React Native
componentDidMount = () ⇒ {
[Link](
(position) ⇒ {
const initialPosition = [Link](position);
[Link]({ initialPosition });
},
(error) ⇒ alert([Link]),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
[Link] = [Link]((position) ⇒ {
const lastPosition = [Link](position);
[Link]({ lastPosition });
});
}
componentWillUnmount = () ⇒ {
[Link]([Link]);
}
render() {
return (
<View style = {[Link]}>
<Text style = {[Link]}>
Initial position:
</Text>
<Text>
{[Link]}
</Text>
86
React Native
</Text>
<Text>
{[Link]}
</Text>
</View>
)
}
}
export default SwichExample
boldText: {
fontSize: 30,
color: 'red',
}
})
87
React Native
When we run the app, we can update the text by typing into the input field.
88
28. React Native – AsyncStorage React Native
In this chapter, we will show you how to persist your data using AsyncStorage.
Step 1 – Presentation
In this step, we will create the src/components/home/[Link] file.
const Home = () ⇒ {
return (
<AsyncStorageExample />
)
}
export default Home
Step 2 – Logic
Name from the initial state is empty string. We will update it from persistent storage when
the component is mounted.
setName will take the text from our input field, save it using AsyncStorage and update
the state.
src/components/home/[Link]
import React, { Component } from 'react'
import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native'
state = {
'name': ''
}
componentDidMount = () ⇒ [Link]('name').then((value) ⇒
[Link]({ 'name': value }))
89
React Native
setName = (value) ⇒ {
[Link]('name', value);
[Link]({ 'name': value });
}
render() {
return (
<View style = {[Link]}>
<TextInput style = {[Link]} autoCapitalize = 'none'
onChangeText = {[Link]}/>
<Text>
{[Link]}
</Text>
</View>
)
}
}
textInput: {
margin: 15,
height: 35,
borderWidth: 1,
backgroundColor: '#7685ed'
}
})
90
React Native
When we run the app, we can update the text by typing into the input field.
91
React Native
To check if the data is persistent, we can just reload the simulator. The text will still be
visible.
92
29. React Native – CameraRoll React Native
Step 1 – Home
In this step, we will create the src/components/home/[Link] file.
src/components/home/[Link]
import React from 'react'
import CameraExample from './[Link]'
const Home = () ⇒ {
return (
<CameraExample />
)
}
npm i react-native-camera@0.6
Step 2 – Permissions
If you use IOS 10, you need to add permissions in ios/reactTutorialApp/[Link].
<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first
time</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first
time</string>
93
React Native
Step 3 - Camera
takePicture method will return a promise and path of the picture.
src/components/home/[Link]
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
render() {
return (
<View style = {[Link]}>
<Camera
ref = {(cam) ⇒ {
[Link] = cam;
}}
style = {[Link]}
aspect = {[Link]}>
</Camera>
94
React Native
}
}
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
fontSize: 30,
color: 'red',
alignSelf: 'center',
}
});
95
React Native
When the app is run, it seeks permission as shown in the following screenshot.
96
React Native
NOTE − To be able to test the Camera on IOS, you must use mobile device since it won't
work on a simulator.
97