You are on page 1of 80

REACT NATIVE

6.1 INTRODUCTION
6.2 ENVIRONMENT SETUP
6.3 JAVASCRIPT ES6 OVERVIEW
UNIT 6
6.4 CREATE REACT NATIVE APP
6.5 REACT NATIVE ALERT API
6.6 REACT NATIVE GEOLOCATION API
6.7 THIRD PART Y LIBRARIES
 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.
REACT NATIVE FEATURES

 Following are the features of React Native −


 React − This is a Framework for building web and mobile apps
using JavaScript.
 Native − You can use native components controlled by
JavaScript.
 Platforms − React Native supports IOS and Android platform.
REACT NATIVE ADVANTAGES

 Follow are the advantages of React Native −


 JavaScript − You can use the existing JavaScript knowledge to
build native mobile apps.
 Code sharing − You can share most of your code on dif ferent
platforms.
 Community − The community around React and React Native
is large, and you will be able to find any answer you need.
REACT NATIVE LIMITATIONS

 Following are the limitations of React Native −


 Native Components − If you want to create native functionality
which is not created yet, you will need to write some platform
specific code.
REACT NATIVE - ENVIRONMENT SETUP

 Step 1: Install create-react-native-app


 After installing NodeJS and NPM successfully in your
system you can proceed with installation of create -
react-native-app (globally as shown below).
 C:\Users\Dipti> npm install -g create-react-native-
app
Step 2: Create project
Browse through required folder and create a
new react native project as shown below.
C:\Users\Dipti>cd Desktop
C:\Users\Dipti\Desktop>create-react-native-
app MyReactNative
 After executing the above command, a folder with specifies
name is created with the following contents.

 Step: Install React Native CLI
 You can install react native command line interface on npm,
using the install -g react-native-cli command as shown below.
 npm install -g react-native-cli
 Start react native
 To verify the installation browse through the project
folder and try starting the project using the start
command.
 C:\Users\Dipti\Desktop>cd MyReactNative
C:\Users\Dipti\Desktop\MyReactNative>npm start
 If everything went well you will get a QR code as shown below .
REACT NATIVE ENVIRONMENT SETUPS

 There is a dif ferent alternative for React Native environment


setup (installation), depends upon the operating system you
use.
 The instructions are quite dif ferent for each development and
target operating system.
 we will use Windows as a development operating system and
Android as a target operating system.
 Developing app using React Native framework requires Node,
React Native command line interface, Python2, JDK, and
Android Studio.
S T E P S T O S E T U P R E AC T N AT I V E E N V I R O N M E N T
1 . V I S I T C H O C O L AT E Y
, A N D C L I C K " I N S TA L L C H O C O L AT E Y N O W " I T O P E N A N O T H E R U R L .

 Here, we are using a favorite package manager Chocolatey for


Windows. Using this, we can install a recent version of Python,
and Java SE Development Kit (JDK )
.
HTTPS://WWW.YOUTUBE.COM/WATCH?V
=-5WLKU_J_AE
 Install chocolatey setup, copy the code provided in Install with
cmd.exe section.

 @"%SystemRoot%\System32\WindowsPowerShell\v1 .0\power
shell.exe" -NoProfile -InputFormat None -ExecutionPolicy
Bypass -Command "iex ((New -Object
System.Net.WebClient).DownloadString('https://chocolatey.or
g/install.ps1'))" && SET
"PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
 React Native Environment Setup
 3. Open your Command Prompt in Administrative mode (right-
click Command Prompt and select "Run as Administrator"),
paste this code and click enter. It will install Chocolatey .
 4. In the Administrative mode of command prompt, paste the
code and run it (install Node.js, Python, and JDK).
 If you have already installed Node.js, make sure it has version
above 8 and if you have already installed JDK, make it version
8 or newer version.
 choco install -y nodejs.install python2 jdk8
 Node comes with npm (Node Package Manager), which lets
you install the React Native. Run the given code:

 npm install -g react-native-cli


 Setup Java JDK and Android SDK path
 1 . Visit How to set path in Java
 to set JDK path.
 2. Set Android SDK path as My Computer > Properties >
Advance system settings > Environment Variables > in System
variables section. Click "New..." add Android home and
Android SDK as bellow screen.
ANDROID PATH

C:\Users\Rakesh\AppData\Lo
cal\Android\Sdk
 3. Install the required components, go to Tools Android > SDK
Manager > SDK platforms and select the required components
and install.
REACT NATIVE FIRST APPLICATION HELLO
WORLD
 Steps to create React Native application
 1 . First, you have to start your emulator (Android Emulator)
and make it live.
 2. Create a directory ( ReactNative) in your any drive.
 3. Open "Command Prompt" and go to your ReactNative
directory.
 4. Write a command react -native init FirstApp to initialize your
app "FirstApp".
 5. Go to your directory location " FirstApp" and run the
command react-native run-android. It will start Node
server and launch your application in virtual device emulator.
 View Code of React Native Application
 Open your one of the favorite JavaScript supportable IDE and
open App.js file inside your FirstApp application.

HELLO WORLD" APPLICATION

 Create a simple "Hello World" app by editing App.js file of


FirstApp.
 Save the application and reload by simply pressing twice "R"
or Ctrl+M (Reload).
 App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react -native';

type Props = {};


export default class App extends Component<Props> {
render() {
return (
<View>
<Text>Hello World</Text>
</View>
);
}
}
Edit simple React Native "Hello World" application
Edit React Native "Hello World" application using StyleSheet.

App.js
impor t React, {Component} from 'react';
impor t {Platform, StyleSheet, Text, View} from 'react -native';

type Props = {};


expor t default class App extends Component<Props> {
render() {
return (
<View>
<Text style={ styles.welcome }>Hello World</Text>
</View>
);
}
}
const styles = StyleSheet.create ({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
}
});
REACT NATIVE BUTTON

 Most users interact with mobile through touches. There are


combinations of gestures that work on it, such as tapping on
the button, zooming the map, scrolling a list, etc.
 A button is one of the components that work on its click.
 React Native Button is a basic component that works by
clicking on it. It imports the Button class of react -native.
Props of Button

Prop Type Required Description


onPress function yes Call the handler when user clicks the
button.
title string yes Display the text inside the button.
accessibili string no Display the text for blindness accessibility
tyLabel features.
color Color no Set the background color of the Android
button or set the color of iOS text.

disabled bool no It disables all interactions for this


component, if true.
textID string no Used to locate this view in end-to-end tests.

hasTVPref bool no It preferred TV focus work only for Apple


erredFocu TV.
s
REACT NATIVE BUTTON EXAMPLE

 In this example, we will work on the button component.


 React Native Button component imports the Button class of
react-native library.
 It has several props such as title, onPress, accessibilityLabel,
etc. which are mentioned above .
 In the below code the title prop sets the title of a
button, onPress prop calls the mention function and performs
an event.
 The color prop sets the color of the button,
and disabled={true} makes the button to disable.
impor t React, { Component } from 'react';
impor t { Aler t, AppRegistr y, Button, StyleSheet , View } from 'react -native';

expor t default class ButtonBasics extends Component {


onPressButton() {
Aler t.aler t('You clicked the button!')
}

render() {
return (
<View style={ styles.container }>
<View style={ styles.buttonContainer }>
<Button
onPress={this.onPressButton }
title="Press Me"
/>
</View>
<View style={ styles.buttonContainer }>
<Button
onPress={this.onPressButton }
title="Press Me"
color="#009933"
/>
< / V i ew >
< V i ew s t y l e = { s t y l e s .m ul t i B ut to n C o n t a i n e r } >
< B u t to n
o n P r e s s = { t hi s . o n P r e s s B ut to n }
t i t l e = " A d i s a b l e d b u t to n "
d i s a b l e d = { t r ue }
/>
< B u t to n
o n P r e s s = { t hi s . o n P r e s s B ut to n }
t i t l e = " OK !"
c o l o r = "# 0 0 9 9 3 3 "
/>
< / V i ew >
< / V i ew >
); } }

c o n s t s t y l e s = S t y l e S h e et . c r e a te ( {
container: {
f l ex : 1 ,
j u s t i f y C o n te n t : ' c e n te r ' ,
},
b u t ton C o n t ai n e r : {
margin: 20
},
m u l t iB ut to n C o n t a i n e r : {
margin: 20,
f l ex D ir ec t i o n : ' r o w ' ,
j u s t i f y C o n te n t : ' s p a c e - b et we e n '
}
})
OUTPUT
React Native Code Explanation
 import React, {Component} from 'react': imports the library
and other components from react module and assign then to
variable React.
 const instruction: sets to display the platform-specific
message.
 export default class App extends Component: defines the
classes that extend the React Component. The export default
class modifier makes the class "public". This block of code
defines the components that represent the user interface.
 render(): a function that returns a React element.
 return(): returns the result of layout and UI components.
 View: a container that supports the layout accessibility
controls. It is a fundamental component for building the UI .
 Text: a React component for displaying text.
 style: a property used for styling the components using
StyleSheet.
 styles: used to design individual components.
 {styles.instructions}>{instructions}:
 const styles = StyleSheet.create({}): The StyleSheet class
creates the style object that controls the layout and
appearance of components. It is similar to Cascading Style
Sheets (CSS) used on the Web.
REACT NATIVE ALERT

 React Native Alert is an API which is used to display an alert


dialog with specified title and message. It uses an alert()
method to prompt an alert dialog.
 This Alert dialog provides three dif ferent lists of buttons
(combination of neutral, negative, and positive) to perform
action. Pressing any of these buttons calls
the onPress callback method and dismiss the alert.
 By default, Alert has only a positive (OK) button.
 The Alert that prompts to enter some information is created
using AlertIOS. It is only supported in iOS.
 React Native Alert in iOS
 In iOS, we can specify number of buttons. Each
buttons can be separately specify a style, which is
one of default, cancel, or destructive.
 React Native Alert in Android
 In Android, the Alert button can be specified with
mainly three buttons. These buttons are a neutral,
negative and a positive button:
 Alert buttons are specified in three dif ferent combinations.
These are:
 If we specify only one button, it will be the 'positive' one (such
as 'OK').
 If we specify two buttons, it will be 'negative' and 'positive'
(such as 'Cancel', 'OK').
 Specifying three buttons means 'neutral', 'negative', 'positive'
(such as 'Later', 'Cancel', 'OK').
 In Android, the alerts are by default dismissed by clicking
outside the alert dialog.
 The dismiss event can be handled by using an optional
parameter, with an onDismiss callback property {
onDismiss: () => {} } . However, we can disable the
dismissing property by using the property {cancelable: false}.
REACT NATIVE ALERT EXAMPLE

 In this example, we create two alerts on two buttons. One


alert contains two options button without cancelable. Other
alert contains three options button with cancelable false.
i m p o r t Re a c t , { C o m p o n e n t } f r o m ' r e a c t ' ;
i m p o r t { A l e r t , A p p Re g i s t r y, B u t to n , S t y l e S h e e t , V i e w } f r o m ' r e a c t - n a t i v e ' ; App.js

e x p o r t d e f a u l t c l a s s B u t to n B a s i c s e x te n d s C o m p o n e n t {
showAlert1() {
Alert.aler t(
'Alert Title',
'My Alert Msg',
[
{
te x t : ' C a n c e l ' ,
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ te x t : ' O K ' , o n P r e s s : ( ) = > c o n s o l e . l o g ( ' O K P r e s s e d ' ) } ,
] ); }
showAlert2() {
Alert.aler t(
'Alert Title',
'My Alert Msg',
[
{ te x t : ' A s k m e l a te r ' , o n P r e s s : ( ) = > c o n s o l e . l o g ( ' A s k m e l a te r p r e s s e d ' ) } ,
{
te x t : ' C a n c e l ' ,
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ te x t : ' O K ' , o n P r e s s : ( ) = > c o n s o l e . l o g ( ' O K P r e s s e d ' ) } ,
],
{cancelable: false}
) }
render() {
return (
<View style={styles.container }>
<View style={styles.buttonContainer }>
< B u t to n
o n P r e s s = { t h i s . s h ow A l e r t 1 }
title="Button 1"
/>
</View>
<View style={styles.buttonContainer }>
< B u t to n
o n P r e s s = { t h i s . s h ow A l e r t 2 }
title="Button 2"
color="#009933"
/>
</View>
</View>
); } }

const styles = StyleSheet.create({


container: {
flex: 1,
j u s t i f y C o n t e n t : ' c e n te r ' ,
},
b u t to n C o n t a i n e r : {
margin: 20
},
multiButtonContainer : {
margin: 20,
f l e x D i r e c t i o n : ' r ow ' ,
j u s t i f y C o n t e n t : ' s p a c e - b e t we e n '
} })
OUTPUT
REACT NATIVE GEOLOCATION

 The Geolocation API is used to get the geographical position


(latitude and longitude) of a place. It extends
the Geolocation web specification. This API is available
through the navigator.geolocation globally, so that we do not
need to import it.
 In Android, Geolocation API uses android.location API.
 This API is not recommended by Google because it is less
accurate, and slower than the recommended Google Location
Services API.
 To use the Google Location Services API in React Native, use
the react-native-geolocation-service module.
REACT NATIVE CONFIGURATION AND
PERMISSIONS
 In this section, we discuss the project which is created
using react-native init or with expo init or Create React Native
App.
 iOS
 For iOS platform we include
the NSLocationWhenInUseUsageDescription key in Info.plist to
enable geolocation. Geolocation is by default enabled when a
project is created with react-native init.
 To enable the geolocation in background, we need to include
the 'NSLocationAlwaysUsageDescription ' key in Info.plist.
 This requires adding location as a background mode in the
'Capabilities' tab in Xcode.
 Android
 To access the location in Android, we need to add <uses-
permission
android:name="android.permission.ACCESS_FINE_LOCATION "
/> in AndroidManifest.xml file.
 The Android API >=23 requires to request
the ACCESS_FINE_LOCATION permission using the
PermissionsAndroid API.
Methods of Geolocation

Method Description
getCurrentPosition() It invokes the success callback once with latest
location information.
watchPosition() It invokes the success callback whenever the
location changes. It returns a watchId (number).

clearWatch() It clears the watchId of watchPosition().


stopObserving() It stops observing for device location changes as
well as it removes all listeners previously registered.

setRNConfiguration( It sets the configuration options, which is used in all


) location requests.
requestAuthorization It requests suitable Location permission based on
() the key configured
APP.JS

import React from 'react';


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

export default class App extends React.Component {


constructor(){
super();
this.state = {
ready: false,
where: {lat:null, lng:null},
error: null
}
}
componentDidMount (){
let geoOptions = {
enableHighAccuracy:false ,
timeOut: 20000, //20 second
// maximumA ge: 1000 //1 second
};
this.setState({ready:false, error: null });
navigator.geolocation.getCurrentPosition ( this.geoSuccess ,
this.geoFailure,
geoOptions);
}
geoSuccess = (position) => {
console.log(position.coords.latitude );

this.setState({
ready:true,
where: {lat: position.coords.latitude,lng:position.coords.longitude
}
})
}
geoFailure = (err) => {
this.setState({error: err.message});
}
CONT…2

render() {
return (
<View style={ styles.container }>
{ !this.state.ready && (
<Text style={ styles.big }>Using Geolocati on in React
Native.</Text>
)}
{ this.state.error && (
<Text style={ styles.big }>Error: {this.state.error }</Text>
)}
{ this.state.ready && (
<Text style={ styles.big }>
Latitude: { this.state.where.lat }
Longitude: { this.state.where.lng }
</Text>
)}
</View>
);
}
}
CONT…3

const styles = StyleSheet.create({


container: {
flex: 1 ,
backgroundColor: '#f f f',
alignItems: 'center',
justifyContent: 'center'
},
big: {
fontSize: 25
}
});
OUTPUT
LINKING AND USING THIRD PART Y
LIBRARIES
 The third par ty Librar y provides the native app features which are not
available in React Native features. If we refer to React Native
documentation, there are lots of features that are not available (such
as maps). Due to this, we need to add third par ty libraries in our
project. In this tutorial, we would learn how to add the third par ties
libraries in our app (adding third par ty icons). There are dif ferent sets
of bundled Icon available. Some of them are listed below:
 AntDesign
 Entypo
 EvilIcons
 Feather
 FontAwesome
 FontAwesome 5
 Foundation
 Ionicons
 MaterialIcons
 MaterialCommunityIcons
 Octicons
 Zocial
 SimpleLineIcons
 Installing Libraries
 There are dif ferent ways and commands to install the libraries
depending upon the development OS and target OS. In this
tutorial, we install the Ionicons libraries. To install the
Ionicons libraries on Windows, run the command: $ npm
install react-native-vector-icons --save.
 Create a project and run ' npm install --save react-native-
vector-icons' as D:\ReactNative\navigationApp>npm install --
save react-native-vector-icons
LINKING LIBRARIES ON ANDROID

 Open your android/settings.gradle file and add the below


code. Here, we are adding only Ionicons library.
 If you want to add others libraries, just add them
in include tag and mention their path and library in android
folder at project as below.
 include ':react-native-vector-icons'
 project(':react-native-vector-icons').projectDir = new
File(rootProject.projectDir, '../node_modules/react-native-
vector-icons/android')
 Now, add the following dependency in
android/app/build.gradle:

 implementation project(':react -native-vector-icons')


 Earlier, upto 2018 the compile term is used in place of
implementation.
In,
android/app/src/main/java/com/{ project_director y}/MainApplicati
on.java

import com.oblador.vectoricons.VectorIconsPackage ;
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new VectorIconsPackage ()
);
}
 To add more libraries, simply separate them with comma and
add libraries packages. The above procedures are common to
add native libraries in the Android.

 Now, in 'android/app/build.gradle' add the following


dependency:
 apply from: "../../node_modules/react-native-vector-
icons/fonts.gradle"
 project.ext.vectoricons = [
 iconFontNames: ['Ionicons.ttf'] // Name of the font files yo
u want to copy
]
 React Native Linking Third Party Library Example
 In this example, we will add the trash icon of the Ionicons
library. Open your project, and import Icon from ' react-native-
vector-icons/Ionicons' package. Search for icon at
ionicons.com which you want to add (in my case ios-trash).
 In the npm doc, you will find the Icon Component and its
properties.
APP.JS

impor t React, {Component} from 'react';


impor t {Platform, StyleSheet , Text, View, TouchableOpacity,Aler t } from 'react -
native';
impor t Icon from 'react -native -vector -i cons/ Ioni cons';

type Props = {};


expor t default class App extends Component<Props> {
deleteItem = ()=>{
Aler t.aler t ("delete icon pressed")
}
render() {
return (
<View style={ styles.container }>
<Text style={ styles.textStyle }>Adding Ionicons librar y</Text>
<TouchableOpacity style={styles.touchableStyle } onPress=
{this.deleteItem } >
<Icon size={30} name=" ios-trash" color="red"/>
</TouchableOpacity >
</View>
); } }
const styles = StyleSheet.create ({
container: {
flex: 1 ,
},
textStyle :{
fontSize:25,
marginTop : 30,
textAlign: 'center',
},
touchableStyle :{
marginTop : 80,
justifyContent : 'center',
alignItems: "flex-end",
marginRight: 50,
}
});
OUTPUT
REACT NATIVE TEXT INPUT

 TextInput is the fundamental component to input text. It has


several props which configure the dif ferent features, such
as onChangeText that takes a function and call it whenever
the text changed. The onSubmitEditing prop takes a function,
which is called when the text submitted.
 There are several things, which can be performed with text
input, such as validating the text inside while user types.
APP.JS

i m p o r t Re a c t , { C o m p o n e n t } f r o m ' r e a c t ' ;
i m p o r t { A p p Re g i s t r y, Tex t , Tex t I n p ut , V i ew } f r o m ' r e a c t - n a t i ve ' ;

ex p o r t d e f a u l t c l a s s P i z z a Tr a n s l a to r ex te n d s C o m p o n e n t {
c o n s t r uc tor (p r o p s ) {
s u p e r ( p ro p s ) ;
t h i s . s t a te = { tex t : ' ' } ;
}

render() {
r et u r n (
< V i ew s t y l e = { { p a d d i n g : 1 0 } } >
< Tex t I n p ut
s t y l e = { { h e i g h t: 4 0 , b a c k g ro un d C o l o r : ' a z u r e ' , f o n t S i z e : 2 0 } }
p l a c e h o ld e r = "Ty p e h e r e to t r a n s l a te ! "
o n C h a n g e Tex t = { ( tex t ) = > t h i s . s et S t a te ( { tex t } ) }
/>
< Tex t s t y l e = { { p a d d i ng : 1 0 0 , f o n t S iz e : 5 0 } } >
{ t h i s . s t a te . tex t . s p l i t ( ' ' ) . m a p ( ( wo r d ) = > w o r d & & ' 🍕 ' ) . j o i n (' ' ) }
< / Tex t > *
< / V i ew >
); } }
PROGRAM OUTPUT
REACT NATIVE LISTVIEW

 React Native ListView is a view component which contains the


list of items and displays in a vertical scrollable list.
 The minimum API to create list view is ListView.DataSource.
 It populates a simple array of data blobs, and instantiate
a ListView component with data source and
a renderRow callback.
 The renderRow takes a blob from data array and returns a
renderable component.
REACT NATIVE LISTVIEW EXAMPLE 1

 Let's create an example of ListView component. In this


example, we create a data source, and fill it with an array
of data blobs. Create a ListView component using that array
as its data source, and pass it in its renderRow callback.
 The renderRow is a function which returns a component which
renders the row.
EXAMPLE
i m p o r t Re a c t , { C o m p o n e n t } f r o m ' r e a c t '
i m p o r t { Tex t , L i s t V i ew, S t y l e S h e et } f r o m ' r e a c t - n a t i ve '

ex p o r t d e f a u l t c l a s s M y L i s t C o mp o n e n t ex te n d s C o m p o n e n t {
c o n s t r uc tor () {
super();
c o n s t d s = n ew L i s t V i ew. D a t a S o urc e ( { row H a s C h a n g e d : ( r 1 , r 2 ) = > r 1 ! = = r 2 } ) ;
t h i s . s t a te = {
d a t a S o urc e : d s . c l o n e Wi t h Row s ( [' A n d r o id ' ,' i O S ' , ' J av a ' , ' P h p ' , ' H a d o o p ' ,
'Sap', 'Python','Ajax', 'C++',
' Ru by ' , ' R a i l s ' , ' . N et ' , ' Pe r l ' ] ) ,
};
}

render() {
r et u r n (
< L i s t V i ew
d a t a S o urc e = { t h i s . s t a te . d a t a S o urc e }
r e n d e r Row = {
(rowData) =>
< Tex t s t y l e = { { fo n t S i z e : 2 0 } } > { row Da t a }< / Tex t > }
/>
); } }
EXPLANATION

 we create an instance of ListViewDataSource in the


constructor. The ListViewDataSource is a parameter and
accept an argument which contain any of these four:
 getRowData(dataBlob, sectionID, rowID)
 getSectionHeaderData(dataBlob, sectionID)
 rowHasChanged(previousRowData, nextRowData)
 sectionHeaderHasChanged(previousSectionData,
nextSectionData)
REACT NATIVE SWITCH

 React Native Switch is a Boolean control component which


sets its value to true or false.
 It has an onValueChange callback method that updates its
value prop.
 If the value prop is not changed, the Switch component
continues supplied the value prop instead of the expected
result of any user actions.
Props of Switch

Props Description
disabled It is a Boolean property, if it is set to true then it cannot be toggled to
switch. Its default value is false.
trackColor It is used to customize the color for switch track.
ios_backgroundColo It set the custom background color in iOS. The background can be
r visible either when the switch value is disabled or when the switch is
false.
onValueChange It invoked when the switch value is changed.
testID It is used to locate this view in end-to-end tests.
thumbColor It colors the foreground switch grip. When it is set to iOS, the switch
grip will lose its drop shadow.
tintColor It sets the border color on iOS and background color on Android when
the switch is turned off. This property is deprecated; use trackColor at
the place of it.

value It is the value of switch. When it is set to true, it turns on. The default
value is false.
i m p o r t Re a c t , { C o m p o n e n t } f r o m ' r e a c t '
i m p o r t { S t y l e S h e e t , S w i t c h , V i e w, Te x t } f r o m ' r e a c t - n a t i v e '

e x p o r t d e f a u l t c l a s s S w i t c h E x a m p l e e x te n d s C o m p o n e n t {
s t a te = {
s w i t c h Va l u e : f a l s e
};

render() {
return (
<View style={styles.container }>
< Te x t s t y l e = { s t y l e s . te x t S t y l e } > S w i t c h E x a m p l e < / Te x t >
< Te x t s t y l e = { s t y l e s . te x t S t y l e } > { t h i s . s t a t e . s w i t c h Va l u e ? ' o n ' : ' o f f ' } < / Te x t >
<Switch
v a l u e = { t h i s . s t a t e . s w i t c h Va l u e }
o n Va l u e C h a n g e = { ( s w i t c h Va l u e ) = > t h i s . s e t S t a t e ( { s w i t c h Va l u e } ) } / >
</View>
);
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
a l i g n I t e m s : ' c e n te r ' ,
j u s t i f y C o n t e n t : ' c e n te r ' ,
},
te x t S t y l e : {
m a r g i n : 24 ,
fontSize: 25,
f o n t We i g h t : ' b o l d ' ,
te x t A l i g n : ' c e n te r ' ,
color: '#344953'
} })

You might also like