React Native StatusBar is a component which is used to decorate status bar of the app. It is used by importing the StatusBar component from the react-native library. We can use multiple StatusBar at the same time.
<View>
<StatusBar
backgroundColor = “#b3e6ff”
barStyle = “dark-content”
/>
</View>
<View>
<StatusBar
backgroundColor = “#b3e6ff”
barStyle = “dark-content”
/>
<View>
<StatusBar
hidden={route.statusBarHidden} />
</View>
</View>
React Native StatusBar Props
Props
Description
animated
A status bar is animated if its property is changed. It supports backgrondColor, hidden, and barStyle.
barStyle
It sets the color of status bar text.
hidden
It is used to hide and show the status bar. By default, it is false. If hidden = {false} it is visible, if hidden = {true}, it hide the status bar.
backgroundColor
It sets the background color of the status bar.
translucent
When it is set of true, the app is built under the status bar.
showHideTransition
It displays the transition effect when showing and hiding the status bar. The default is ‘fade’.
networkActivityIndicatorVisible
It checks the network activity indicator is visible or not. It supports in iOS.
React Native StatusBar Methods
setHidden
setBarStyle
setBackgroundColor
setNetworkActivityIndicatorVisible
setTranslucent
React Native StatusBar Example 1
Let’s create a simple StatusBar example in which we change its background color.
React Native Picker is component which is used to select an item from the multiple choices. This is the same as a Dropdown option. Picker is used when we need to provide an alternative to choose from multiple options.
It is used by importing the Picker component from the react-native library.
Props of Picker
Prop
Description
onValueChange( itemValue, itemPosition)
It is a callback prop and called when an item is selected. It takes two parameters (itemValue: the item (value) which is selected, itemPosition: the position (index) of a selected item).
selectedValue
Returns the selected value.
style
It is a picket style type.
testID
It is used to locate this view in end-to-end tests.
enabled
It is a Boolean prop which makes picker disable when set to false. If it is set to false, the user cannot be able to make a selection.
mode
On Android, it specifies how to display the selections items when the users click on the picker. It has the “dialog” and “dropdown” properties. The dialog is default mode and shows as a modal dialog. The dropdown displays the picker as dropdown anchor view.
prompt
It is used in Android with dialog mode as the title of the dialog.
itemStyle
It styles each item of the picker labels.
React Native Picker Example
In this example, we create three label items in Picker component. When the item is selected from Picker, it calls the onValueChange callback and set the selected item in the picker. The index of item is read from itemPosition. The item’s position is displayed in a Text component.
App.js
import React, { Component } from ‘react’
import {StyleSheet,View, Text,Picker} from ‘react-native’
ActivityIndicator is used to display a circular loading indicator.
Props
Props
Description
animating
Option to show the indicator (bydefault it is true) or hide it (false).
size
Set the size of indicator (‘small’,’large’, number). The default size is small. Number format support only in android.
color
Set the foreground color of the spinner (default is gray).
hidesWhenStopped
It provides an option to show or hide the indicator when there is no animating (true by default).
React Native ActivityIndicator Example
In this example, the animating property set the activity indicator to true, and it is visible on the screen. When the component mounts, the animated activity indicator will be closed after six seconds using the closeActivityIndicator() method.
TextInput is the fundamental component to input text. It has several props which configure the different 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.
React Native TextInput Example 1
In this example, we create a TextInput and perform an onChangeText action. At every text change, it calls the setState and checks the condition of a split. If the input text found ‘ ‘ space, it displays ‘?’ in the text. The text is placed in state as it is changed every time.
import React, { Component } from ‘react’;
import { AppRegistry, Text, TextInput, View } from ‘react-native’;
export default class PizzaTranslator extends Component {
{this.state.text.split(‘ ‘).map((word) => word && ‘?’).join(‘ ‘)}
</Text>*
</View>
);
}
}
Output
TextInput properties
allowFontScaling
autoCapitalize
autoCorrect
autoFocus
blurOnSubmit
caretHidden
clearButtonMode
clearTextOnFocus
contextMenuHidden
dataDetectorTypes
defaultValue
disableFullscreenUI
editable
enablesReturnKeyAutomatically
inlineImageLeft
inlineImagePadding
keyboardAppearance
keyboardType
maxLength
multiline
numberOfLines
onBlur
onChange
onChangeText
onContentSizeChange
onEndEditing
onFocus
onKeyPress
onLayout
onScroll
onSelectionChange
onSubmitEditing
placeholder
placeholderTextColor
returnKeyLabel
returnKeyType
scrollEnabled
secureTextEntry
selection
selectionColor
selectionColor
selectionState
selectTextOnFocus
spellCheck
textContentType
style
textBreakStrategy
underlineColorAndroid
The method .focus() and .blur() are exposed from the native element. These methods focus or blur the TextInput programmatically.
Multiline TextInput
The multiline props provide facility to input multiple lines of text. Some props of TextInput are only compatible with multiline, for example, multiline={true/false}. The property borderButtomColor will not work if multiline = false.
React Native TextInput Example 2
import React, { Component } from ‘react’;
import { AppRegistry, View, TextInput } from ‘react-native’;
class UselessTextInput extends Component {
render() {
return (
<TextInput
{…this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below
editable = {true}
maxLength = {40}
/>
);
}
}
export default class UselessTextInputMultiline extends Component {
Touchable components provide the capability to capture the tapping functionality. The touchables component can be implemented as an alternative of basic button, if they are not look right for your app. Using these components, you build your own button. Tapping on these components, you can display the feedback.
The touchables components do not provide any default styling, so you will need to do your style for presenting nicely in the app.
Types of Touchable Components
There are four touchable components provided by React Native. Selection of this component depends on the kind of feedback you want to provide:
TouchableHighlight
TouchableNativeFeedback
TouchableOpacity
TouchableWithoutFeedback.
React Native TouchableHighlight
The TouchableHighlight can be used where you would use a button or link on the web. The background of this component becomes dark on pressing it.
Props
Props
Type
Required
Platform
Description
activeOpacity
number
no
Determines the opacity of wrapped view when it is touched.
onHideUnderlay
function
no
Calls instantly after the underlay is hidden.
onShowUnderlay
function
no
Calls instantly after the underlay is shown.
style
View.style
no
underlayColor
color
no
Show the underlay color when the touch is active.
hasTVPreferredFocus
bool
no
iOS
It focuses TV preferred, work only for iOS.
tvParallaxProperties
object
no
iOS
It is an object with properties which control the Apple TV parallax effects.
React Native TouchableNativeFeedback
The TouchableNativeFeedback makes a view to response properly on touch. This component works only for Android operating system. It uses native state drawable to display the touch feedback.
It supports only a single View instance as a child node. It is implemented by replacing the View with another instance of RCTView node.
Props
Props
Type
Required
Description
background
backgroundPropType
no
It determines the background drawable that is going to be displayed as feedback.
useForeground
bool
no
It adds the ripple effect to the foreground of the view, instead of the background.
React Native TouchableOpacity
The TouchableOpacity wrapper is used to reduce the opacity of button. It allows background to be seen while the user press down. The opacity of button will be controlled by wrapping the children in an Animation.
Props
Props
Type
Required
Platform
Description
activeOpacity
number
no
It determines the opacity of wrapped view when it is touched.
tvParallaxProperties
object
no
iOS
It is an object with property which is used to control the Apple TV parallax effects.
hasTVPreferredFocus
bool
no
iOS
It focuses TV preferred, it works on Apple TV only.
Methods
Method
Description
setOpacityTo()
It animates the touchable to a new opacity.
React Native TouchableWithoutFeedback
The TouchableWithoutFeedback is used when the user wants to handle the tap functionality but doesn’t want to display any feedback.
Props
Props
Type
Required
Description
hitSlop
object
no
This defines how far your touch can start away from the button.
onAccessibilityTap
function
no
If accessible is set to true, the system invokes this function when the user performs accessibility tap gesture.
accessibilityHint
string
no
It helps user to understand what will happen when they perform an action on the accessibility element.
accessibilityLabel
node
no
It overrides the text, which is read by the screen reader when users interact with the element.
delayLongPress
number
no
It delays the onLongPress in milli-second calling onPressIn.
Some time user presses a view and holds it for the set of time. This long press is handled by the function using onLongPress props of any of the above “Touchable” components.
The React Native SectionList component is a list view component which sets the list of data into broken logical section. The broken data can be implemented using its section header prop renderSectionHeader.
To implement the SectionList component, we need to import SectionList from ‘react-native’ library.
Props of SectionList
sections
renderItem
initialNumToRender
keyExtractor
renderSectionHeader
renderSectionFooter
onRefresh
inverted
extraData
onEndReached
keyExtractor
legacyImplementation
onViewableItemsChanged
refreshing
removeClippedSubviews
ListHeaderComponent
SectionSeparatorComponent
stickySectionHeadersEnabled
onEndReachedThreshold
ListEmptyComponent
React Native SectionList Example
In this example, we create a SectionList with title and data. The sections prop is used to create the list of title and data values. The renderSectionHeader displays the header section of the list view.
import React, { Component } from ‘react’;
import { AppRegistry, SectionList, StyleSheet, Text, View } from ‘react-native’;
ItemSeparatorComponent prop adds the Separator between the lists of data. Using this prop, call a renderSeparatormethod in which we add a View component as separator.
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: “100%”,
backgroundColor: “#000”,
}}
/>
);
};
ItemSeparatorComponent={this.renderSeparator}
Performing action on SectionList items
To perform an action on clicking (pressing) the list item, we use a onPress prop. The onPress prop and handle the event in another method getListViewItem.
The FlatList component displays the similar structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time. The FlatList shows only those renders elements which are currently displaying on the screen, not all the elements of the list at once.
The FlatList component takes two required props: data and renderItem.
The data is the source of elements for the list, and renderItem takes one item from the source and returns a formatted component to render.
To implement the FlatList component, we need to import FlatList from ‘react-native’ library.
React Native FlatList Example
In this example, we provide hardcoded elements to data prop. Each element in the data props is rendered as a Text component.
The ItemSeparatorComponent prop of FlatList is used to implement the separator between the elements of the list. To perform the click event on list items, we use onPress prop to Text.
import React, { Component } from ‘react’;
import { AppRegistry, FlatList,
StyleSheet, Text, View,Alert } from ‘react-native’;
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.
Note: The ListView component has deprecated. To implement the list component use new list components FlatList or SectionList.
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.
import React, { Component } from ‘react’
import { Text, ListView, StyleSheet } from ‘react-native’
In the above code, we create an instance of ListViewDataSource in the constructor. The ListViewDataSource is a parameter and accept an argument which contain any of these four:
Add separation and perform action on ListView items
Separation is added to provide a separate block and for better display of list items. The props renderSeparator is used to add separator among the items (data) of ListView.
Implement onPress props over Text to perform an action on clicking the list items. Here, we generate an alert message and display the list items on which a user click.
import React from ‘react’;
import { View, ListView, StyleSheet, Text,Alert} from ‘react-native’;
The ScrollView is a generic scrollable container, which scrolls multiple child components and views inside it. In the ScrollView, we can scroll the components in both direction vertically and horizontally. By default, the ScrollView container scrolls its components and views in vertical. To scroll its components in horizontal, it uses the props horizontal: true (default, horizontal: false).
Props of ScrollView
alwaysBounceVertical
onScroll
horizontal
contentContainerStyle
scrollEnabled
bouncesZoom
zoomScale
onScrollBeginDrag
onContentSizeChange
maximumZoomScale
minimumZoomScale
onScrollBeginDrag
onContentSizeChange
maximumZoomScale
minimumZoomScale
onScrollEndDrag
centerContent
contentInset
refreshControl
pagingEnabled
scrollsToTop
snapToAlignment
showsHorizontalScrollIndicator
snapToStart
snapToEnd
indicatorStyle
showsHorizontalScrollIndicator
React Native ScrollView Example
In this example, we create a vertical ScrollView using Text and Button components.
The horizontal ScrollView scrolls the components and views from left to right. It will be implemented by setting the props horizontal to true (horizontal={true}).
In the previous article Layout and Flexbox, we discuss about the Flexbox and its properties. In this tutorial, we will set the position of elements with Flex.
Example 1
Create a View component and place two elements TextInput and Button. The View component with flex property (1) occupy full space of device. The elements TextInput and Button are set in default flex axis (as column).
import React, { Component } from “react”;
import { StyleSheet, TextInput, View , Button } from “react-native”;
export defaultclass App extends Component {
state = {
placeName: “”,
places: []
};
placeNameChangedHandler = val => {
this.setState({
placeName: val
});
};
placeSubmitHandler = () => {
alert(“button clicked”)
};
render() {
return (
<View style={styles.container}>
<TextInput
placeholder=”An awesome place”
onChangeText={this.placeNameChangedHandler}
style={styles.placeInput}
/>
<Button
title=”Button”
onPress={this.placeSubmitHandler}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 26,
backgroundColor: “#fff”,
justifyContent: “flex-start”
}
});
Output:
Example 2
In this example, we will place the Button right to TextInput element. Add a child View component inside parent View with flex: 1 and flexDirtection : “row”. Setting flex: 1 for inner View occupies whole space from top to bottom and left to right. The flexDirtection: “row” set the elements in row-wise inside the inner View component.
import React, { Component } from “react”;
import { StyleSheet, View, TextInput, Button } from “react-native”;
export defaultclass App extends Component {
state = {
placeName: “”,
places: []
};
placeNameChangedHandler = val => {
this.setState({
placeName: val
});
};
placeSubmitHandler = () => {
alert(“button clicked”)
};
render() {
return (
<View style={styles.container}>
<View style={styles.innerContainer}>
<TextInput
placeholder=”An awesome place”
onChangeText={this.placeNameChangedHandler}
/>
<Button
title=”Button”
onPress={this.placeSubmitHandler}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 26,
backgroundColor: “#fff”,
justifyContent: “flex-start”
},
innerContainer:{
flex: 1,
flexDirection: “row”
}
});
Output:
The flex: 1 for inner View occupy full space which does not look good as the TextInput and Button occupy all space from top to bottom.
Example 3
In this example, we remove flex property of inner View and add width: 100%. Removing flex form inner View set the default dimension of elements. Setting width :”100%” for inner View occupy full width and default height of elements.
import React, { Component } from “react”;
import { StyleSheet, View, TextInput, Button } from “react-native”;