React native Key Points

Saismita Lenka
7 min readMay 10, 2021

First release on: March 26, 2015

Current version: 0.64.0 / March 12, 2021

Create react native project: react-native init FirstProject

Run the app in device: react-native run-android / react-native run-ios // better to use xcode for the ios build system

React Native — App

// App.js
import React from 'react';
import { Text, View } from 'react-native';

export default class App extends React.Component {
render() {
return (
<View>
<Text>Welcome to Buggu Buggie's Techno</Text>
</View>
);
}
}

Code Explanation:

import React from 'react'; // import React to be able to use JSX, which will then be transformed to the native components of each platform.

import { Text, View } from 'react-native'; // Textand View are components from react-native

export default class App extends React.Component // Here we find the App class, which is a class component. This class returns a View component with aText as its child.

The Text component allows us to render a text, while the View component renders a container.

React Native — State & Props

The data inside React Components is managed by state and props, and both are objects.

State:

// ParentComponent.js - For explaining state objectstate = {
myState: 'Lorem ipsum dolor sit amet' // Assign the initial value
}
updateState = () ⇒ this.setState({ myState: 'The state is updated' }) // Updating the state objectrender() {
return (
<View>
<ChildComponent myState = {this.state.myState} updateState = {this.updateState}/>
</View>
);

Props:

// ChildComponent
const ChildComponent = (props) => {
return (
<View>
<Text onPress = {props.updateState}>
{props.myState}
</Text>
</View>
)
}

Difference between State and Props:

1. State: Mutable - Can be updated in future
Props: Immutable - Cannot be update

2. State: Changeable
Props: Readonly

3. State: Contains “private” information for the component to initialise, change, and use on its own.
Props: Contains the information set by the parent component (although defaults can be set) and should not be changed.

4. State: reserved only for interactivity, that is, data that changes over time.
Props: way of passing data from parent to child.

React Native — Styling

We will import the StyleSheet. At the bottom of the file, we will create our stylesheet and assign it to the styles constant. In 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 = {styles.myText} property to the Text element.

import { Text, View, StyleSheet } from 'react-native'
...
<View>
<Text style = {styles.myText}>
{props.myState}
</Text>
</View>
...
const styles = StyleSheet.create ({
myState: {
marginTop: 20,
textAlign: 'center',
color: 'blue',
fontWeight: 'bold',
fontSize: 20
}
})

React Native — Flexbox

To accommodate different screen sizes, It offers Flexbox support.

three main properties − flexDirection justifyContent and alignItems.

a) flexDirection — (’column’, ‘row’) : Used to specify if elements will be aligned vertically or horizontally.

b) justifyContent —( ’center’, ‘flex-start’, ‘flex-end’, ‘space-around’, ‘space-between’ ) : Elements be distributed inside the container i.e Vertically centered.

c) alignItems — (’center’, ‘flex-start’, ‘flex-end’, ‘stretched’) : Elements be distributed inside the container along the secondary axis i.e Horizontally centered.

React Native — Text Input, ScrollView, List

Text Input:

Used this for input box.

import { ..., TextInput} from 'react-native'
...
<TextInput style = {styles.input}
underlineColorAndroid = "transparent"
placeholder = "Email"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText = {this.handleEmail}/>
...

ScrollView:

Used this for scrollable the list or content in device.

List:

Listing the array of items and rerender each one by using the map().

...
class List extends Component {
state = {
names: [
{
id: 0,
name: 'Ben',
},
{
id: 1,
name: 'Susan',
},
{
id: 2,
name: 'Robert',
},
{
id: 3,
name: 'Mary',
}
]
}
...
<View>
{
this.state.names.map((item, index) => (
<TouchableOpacity
key = {item.id}
style = {styles.container}
onPress = {() => this.alertItemName(item)}>
<Text style = {styles.text}>
{item.name}
</Text>
</TouchableOpacity>
))
}
</View>
...

React Native — Images

It will use for attaching images in our application.

Local folder:

import { Image } from 'react-native'

...
<Image source = {require('C:/Users/Tutorialspoint/Desktop/NativeReactSample/logo.png')} />
...

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@2x.jpg
my-image@3x.jpg

Network Images:

Instead of require, we need the source property. It is recommended to define the width and the height for network images.

import { View, Image } from 'react-native'

...
<Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
style = {{ width: 200, height: 200 }}
/>

React Native — HTTP

It uses fetch for handling network requests.

Here 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.

componentDidMount = () => {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}

React Native — Buttons

It can be used as a generic button

import { Button } from 'react-native'
...
<Button
onPress = {handlePress}
title = "Red button!"
color = "red"
/>
...

Touchable Opacity:

This element will change the opacity of an element when touched.

import { TouchableOpacity, ... } from 'react-native'
...
<TouchableOpacity>
<Text style = {styles.text}>
Button
</Text>
</TouchableOpacity>
...

Touchable Highlight:

When a user presses the element, it will get darker and the underlying color will show through.

import { TouchableHighlight, ... } from 'react-native'
...
<TouchableHighlight>
<Text style = {styles.text}>
Button
</Text>
</TouchableHighlight>
...

Touchable Native Feedback:

This will simulate ink animation when the element is pressed.

import { TouchableNativeFeedback, ... } from 'react-native'
...
<TouchableNativeFeedback>
<Text style = {styles.text}>
Button
</Text>
</TouchableNativeFeedback>
...

Touchable Without Feedback:

This should be used when you want to handle the touch event without any animation Usually, this component is not used much.

<TouchableWithoutFeedback>
<Text>
Button
</Text>
</TouchableWithoutFeedback>

React Native — Animations

We will take the example of Expand and Collapse.

import React, { Component } from 'react'
import { View, StyleSheet, Animated, TouchableOpacity } from 'react-native'

class Animations extends Component {
componentWillMount = () => {
this.animatedWidth = new Animated.Value(50)
this.animatedHeight = new Animated.Value(100)
}
animatedBox = () => {
Animated.timing(this.animatedWidth, {
toValue: 200,
duration: 1000
}).start()
Animated.timing(this.animatedHeight, {
toValue: 500,
duration: 500
}).start()
}
render() {
const animatedStyle = { width: this.animatedWidth, height: this.animatedHeight }
return (
<TouchableOpacity style = {styles.container} onPress = {this.animatedBox}>
<Animated.View style = {[styles.box, animatedStyle]}/>
</TouchableOpacity>
)
}
}
export default Animations

const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center'
},
box: {
backgroundColor: 'blue',
width: 50,
height: 100
}
})

React Native — Debugging

You can open the developer menu on the IOS simulator by pressing command + D.

On Android emulator, you need to press command + M.

  • Reload − Used for reloading simulator. You can use shortcut command + R
  • Debug JS Remotely − Used for activating debugging inside browser developer console.
  • 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.

React Native — View

Equivalent of the div element used in web development.

Use Cases:

  • Wrap the elements inside the container, we can use View as a container element.

e.g:

<View>
<Text>Button </Text>
</View>
  • Nest more elements inside the parent element, both parent and child can be View. It can have as many children as you want.

e.g:

<View>
<View>
<Text>Child 1</Text>
</View>
<View>
<Text>Child 2</Text>
</View>
</View>
  • Style different elements, you can place them inside View since it supports style property, flexbox etc.

e.g:

<View style={styles.parentContain}>
<View style={styles.childContain}>
<Text>Child 1</Text>
</View>
<View style={styles.childContain}>
<Text>Child 2</Text>
</View>
</View>
  • View also supports synthetic touch events, which can be useful for different purposes.

e.g:

<View onPress={()=>pressMe()}>
<Text>Button </Text>
</View>

React Native — WebView

It is used when you want to render web page to your mobile app inline.

import { View, WebView, StyleSheet } from 'react-native'
...
<View style = {styles.container}>
<WebView
source = {{ uri:
'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=xyz' }}
/>
</View>
...

React Native — ActivityIndicator

It is a small loader to display on screen.

import { ActivityIndicator, ... } from 'react-native';

...
state = { animating: true }

<View style = {styles.container}>
<ActivityIndicator
animating = {animating}
color = '#bc2b78'
size = "large"
style = {styles.activityIndicator}/>
</View>
...

React Native — Status Bar

It will control the status bar appearance in Android.

import { StatusBar } from 'react-native'

...
<StatusBar barStyle = "dark-content" hidden = {false} backgroundColor = "#00BCD4" translucent = {true}/>
...

React Native — Geolocation

Use for getting the location.

// Component
state = {
initialPosition: 'unknown',
lastPosition: 'unknown',
}
watchID: ?number = null;
componentDidMount = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
const initialPosition = JSON.stringify(position);
this.setState({ initialPosition });
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
this.watchID = navigator.geolocation.watchPosition((position) => {
const lastPosition = JSON.stringify(position);
this.setState({ lastPosition });
});
}
componentWillUnmount = () => {
navigator.geolocation.clearWatch(this.watchID);
}

React Native — AsyncStorage

Used for storing the data in local storage.

import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native'

class AsyncStorageExample extends Component {
state = {
'name': ''
}
componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))

setName = (value) => {
AsyncStorage.setItem('name', value);
this.setState({ 'name': value });
}

React Native Limitations

  • Native Components − If you want to create native functionality which is not created yet, you will need to write some platform specific code.

HAPPY CODING … 😊

--

--