Category: 1. React Native

https://static.vecteezy.com/system/resources/previews/049/401/766/non_2x/react-icon-on-white-square-button-free-png.png

  • React Native FlatList

    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.

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, FlatList,  
    3.     StyleSheet, Text, View,Alert } from ‘react-native’;  
    4.   
    5. export default class FlatListBasics extends Component {  
    6.   
    7.     renderSeparator = () => {  
    8.         return (  
    9.             <View  
    10.                 style={{  
    11.                     height: 1,  
    12.                     width: “100%”,  
    13.                     backgroundColor: “#000”,  
    14.                 }}  
    15.             />  
    16.         );  
    17.     };  
    18.     //handling onPress action  
    19.     getListViewItem = (item) => {  
    20.         Alert.alert(item.key);  
    21.     }  
    22.   
    23.     render() {  
    24.         return (  
    25.             <View style={styles.container}>  
    26.                 <FlatList  
    27.                     data={[  
    28.                         {key: ‘Android’},{key: ‘iOS’}, {key: ‘Java’},{key: ‘Swift’},  
    29.                         {key: ‘Php’},{key: ‘Hadoop’},{key: ‘Sap’},  
    30.                         {key: ‘Python’},{key: ‘Ajax’}, {key: ‘C++’},  
    31.                         {key: ‘Ruby’},{key: ‘Rails’},{key: ‘.Net’},  
    32.                         {key: ‘Perl’},{key: ‘Sap’},{key: ‘Python’},  
    33.                         {key: ‘Ajax’}, {key: ‘C++’},{key: ‘Ruby’},  
    34.                         {key: ‘Rails’},{key: ‘.Net’},{key: ‘Perl’}  
    35.                     ]}  
    36.                     renderItem={({item}) =>  
    37.                         <Text style={styles.item}  
    38.                               onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}  
    39.                     ItemSeparatorComponent={this.renderSeparator}  
    40.                 />  
    41.             </View>  
    42.         );  
    43.     }  
    44. }  
    45.   
    46. const styles = StyleSheet.create({  
    47.     container: {  
    48.         flex: 1,  
    49.     },  
    50.     item: {  
    51.         padding: 10,  
    52.         fontSize: 18,  
    53.         height: 44,  
    54.     },  
    55. })  
    56.   
    57.   
    58. AppRegistry.registerComponent(‘AwesomeProject’, () => FlatListBasics);  

    Output:

    React Native FlatList
    React Native FlatList
  • 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.

    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.

    1. import React, { Component } from ‘react’  
    2. import { Text, ListView, StyleSheet } from ‘react-native’  
    3.   
    4. export default class MyListComponent extends Component {  
    5.     constructor() {  
    6.         super();  
    7.         const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  
    8.         this.state = {  
    9.             dataSource: ds.cloneWithRows([‘Android’,’iOS’, ‘Java’,’Php’, ‘Hadoop’,  
    10.                 ‘Sap’, ‘Python’,’Ajax’, ‘C++’,  
    11.                 ‘Ruby’, ‘Rails’,’.Net’, ‘Perl’]),  
    12.         };  
    13.     }  
    14.   
    15.     render() {  
    16.         return (  
    17.             <ListView  
    18.                 dataSource={this.state.dataSource}  
    19.                 renderRow={  
    20.                     (rowData) =>  
    21.                         <Text style={{fontSize: 20}}>{rowData}</Text>}  
    22.             />  
    23.         );  
    24.     }  
    25. }  

    Output:

    React Native ListView

    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:

    • getRowData(dataBlob, sectionID, rowID)
    • getSectionHeaderData(dataBlob, sectionID)
    • rowHasChanged(previousRowData, nextRowData)
    • sectionHeaderHasChanged(previousSectionData, nextSectionData)

    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.

    1. import React from ‘react’;  
    2. import { View, ListView, StyleSheet, Text,Alert} from ‘react-native’;  
    3.   
    4. class ListViewDemo extends React.Component {  
    5.     constructor(props) {  
    6.         super(props);  
    7.   
    8.         const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  
    9.         this.state = {  
    10.             dataSource: ds.cloneWithRows([ “Android”,  
    11.                 “iOS”,”Java”,”Swift”,  
    12.                 “Php”,”Hadoop”,”Sap”,  
    13.                 “Python”,”Ajax”, “C++”,  
    14.                 “Ruby”, “Rails”,”.Net”,  
    15.                 “Perl”,  
    16.             ])  
    17.         };  
    18.     }  
    19.     //handling onPress action  
    20.     getListViewItem = (rowData) => {  
    21.         Alert.alert(rowData);  
    22.     }  
    23.     render() {  
    24.         return (  
    25.                 <ListView  
    26.                     style={styles.container}  
    27.                     dataSource={this.state.dataSource}  
    28.                     renderRow={(rowData) =>  
    29.                        <Text style={styles.rowViewContainer}  
    30.                              onPress={this.getListViewItem.bind(this, rowData)}>{rowData}  
    31.                        </Text>  
    32.                     }  
    33.                     renderSeparator={(sectionId, rowId) =>  
    34.                         <View key={rowId} style={styles.separator} />}//adding separation  
    35.                 />  
    36.         );  
    37.     }  
    38. }  
    39.   
    40. const styles = StyleSheet.create({  
    41.     container: {  
    42.         flex: 1,  
    43.         backgroundColor: “#e5e5e5”  
    44.     },  
    45.     separator: {  
    46.         height: 0.5, width: “100%”, backgroundColor: “#000”  
    47.     },  
    48.     rowViewContainer: {  
    49.         flex: 1,  
    50.         paddingRight: 15,  
    51.         paddingTop: 13,  
    52.         paddingBottom: 13,  
    53.         borderBottomWidth: 0.5,  
    54.         borderColor: ‘#c9c9c9’,  
    55.         flexDirection: ‘row’,  
    56.         alignItems: ‘center’,  
    57.         fontSize: 20,  
    58.         marginLeft: 10,  
    59.     },  
    60. });  
    61.   
    62. export default ListViewDemo;  

    Output:

    React Native ListView
    React Native ListView
  • React Native ScrollView

    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

    alwaysBounceVerticalonScrollhorizontal
    contentContainerStylescrollEnabledbouncesZoomzoomScale
    onScrollBeginDragonContentSizeChangemaximumZoomScaleminimumZoomScale
    onScrollBeginDragonContentSizeChangemaximumZoomScaleminimumZoomScale
    onScrollEndDragcenterContentcontentInsetrefreshControl
    pagingEnabledscrollsToTopsnapToAlignmentshowsHorizontalScrollIndicator
    snapToStartsnapToEndindicatorStyleshowsHorizontalScrollIndicator

    React Native ScrollView Example

    In this example, we create a vertical ScrollView using Text and Button components.

    App.js

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, ScrollView, Image, Text, Button, StyleSheet } from ‘react-native’;  
    3.   
    4. export default class ScrolledViewExample extends Component {  
    5.     onPressButton() {  
    6.         alert(‘You clicked the button!’)  
    7.     }  
    8.   
    9.     render() {  
    10.         return (  
    11.             <ScrollView >  
    12.                 <Text style={{fontSize:20}}>Scroll me plz</Text>  
    13.                 <Button title={‘Button 1’} onPress={this.onPressButton} />  
    14.                 <Text style={{fontSize:20}}>React Native Example of ScrollView</Text>  
    15.                 <Button title={‘Button 2’} onPress={this.onPressButton}/>  
    16.                 <Text style={{fontSize:20}}>React Native ScrollView Example</Text>  
    17.                 <Button title={‘Button 3’} onPress={this.onPressButton}/>  
    18.                 <Text style={{fontSize:20}}>If you like</Text>  
    19.                 <Button title={‘Button 4’} onPress={this.onPressButton}/>  
    20.                 <Text style={{fontSize:20}}>Scrolling down</Text>  
    21.                 <Button title={‘Button 5’} onPress={this.onPressButton}/>  
    22.                 <Text style={{fontSize:20}}>Scrolling down</Text>  
    23.                 <Button title={‘Button 6’} onPress={this.onPressButton}/>  
    24.                 <Text style={{fontSize:20}}>What’s the best</Text>  
    25.                 <Button title={‘Button 7’} onPress={this.onPressButton}/>  
    26.                 <Text style={{fontSize:20}}>What’s the best</Text>  
    27.                 <Button title={‘Button 8’} onPress={this.onPressButton}/>  
    28.                 <Text style={{fontSize:20}}>Framework around?</Text>  
    29.                 <Button title={‘Button 9’} onPress={this.onPressButton}/>  
    30.                 <Text style={{fontSize:20}}>Framework around?</Text>  
    31.                 <Button title={‘Button 10’} onPress={this.onPressButton}/>  
    32.                 <Text style={{fontSize:20}}>React Native</Text>  
    33.                 <Button title={‘Button 11’} onPress={this.onPressButton}/>  
    34.                 <Text style={{fontSize:20}}>Scroll me plz</Text>  
    35.                 <Button title={‘Button 12’} onPress={this.onPressButton} />  
    36.                 <Text style={{fontSize:20}}>Scroll me plz</Text>  
    37.                 <Button title={‘Button 13’} onPress={this.onPressButton}/>  
    38.                 <Text style={{fontSize:20}}>If you like</Text>  
    39.                 <Button title={‘Button 14’} onPress={this.onPressButton}/>  
    40.                 <Text style={{fontSize:20}}>If you like</Text>  
    41.                 <Button title={‘Button 15’} onPress={this.onPressButton}/>  
    42.                 <Text style={{fontSize:20}}>Scrolling down</Text>  
    43.                 <Button title={‘Button 16’} onPress={this.onPressButton}/>  
    44.             </ScrollView>  
    45.         );  
    46.     }  
    47. }  
    48. // skip this line if you are using Create React Native App  
    49. AppRegistry.registerComponent(‘AwesomeProject’, () => ScrolledViewExample);  

    Output:

    React Native ScrollView
    React Native ScrollView

    React Native Horizontal ScrollView Example

    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}).

    App.js

    1. import React, { Component } from ‘react’;  
    2. import { AppRegistry, ScrollView, View, Image, Text, Button, StyleSheet } from ‘react-native’;  
    3.   
    4. export default class ScrolledViewExample extends Component {  
    5.     onPressButton() {  
    6.         alert(‘You clicked the button!’)  
    7.     }  
    8.   
    9.     render() {  
    10.         return (  
    11.             <ScrollView  horizontal={true} style={styles.container}>  
    12.                 <Text style={{fontSize:22, padding: 10}}>Horizontal ScrollView</Text>  
    13.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    14.                     <Button  
    15.                         onPress={this.onPressButton}  
    16.                         title=”Button 1″  
    17.                         color=”#FF3D00″  
    18.                     />  
    19.                 </View>  
    20.                 <Text style={{fontSize:22, padding: 10}}>javatpoint</Text>  
    21.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    22.                     <Button  
    23.                         onPress={this.onPressButton}  
    24.                         title=”Button 2″  
    25.                         color=”#3D00FF”  
    26.                     />  
    27.                 </View>  
    28.                 <Text style={{fontSize:22, padding: 10}}>React Native ScrollView Example</Text>  
    29.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    30.                     <Button  
    31.                         onPress={this.onPressButton}  
    32.                         title=”Button 3″  
    33.                         color=”#FFFF3D”  
    34.                     />  
    35.                 </View>  
    36.                 <Text style={{fontSize:22, padding: 10}}>If you like</Text>  
    37.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    38.                     <Button  
    39.                         onPress={this.onPressButton}  
    40.                         title=”Button 4″  
    41.                         color=”#FF3DFF”  
    42.                     />  
    43.                 </View>  
    44.                 <Text style={{fontSize:22, padding: 10}}>Scrolling horizontal</Text>  
    45.                 <View style={[{ width: 220,height: 70,padding: 10 }]}>  
    46.                     <Button  
    47.                         onPress={this.onPressButton}  
    48.                         title=”Button 5″  
    49.                         color=”#3DFF00″  
    50.                     />  
    51.                 </View>  
    52.             </ScrollView>  
    53.         );  
    54.     }  
    55. }  
    56. const styles = StyleSheet.create({  
    57.     container:{  
    58.         flex: 1,  
    59.     },  
    60. /*    buttonStyle:{ 
    61.         height: 50, 
    62.         width: 70, 
    63.     }*/  
    64. })  
    65. // skip this line if you are using Create React Native App  
    66. AppRegistry.registerComponent(‘AwesomeProject’, () => ScrolledViewExample);  

    Output:

    React Native ScrollView
    React Native ScrollView
  • Positioning Element with Flex

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

    1. import React, { Component } from “react”;  
    2. import { StyleSheet, TextInput, View , Button } from “react-native”;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         placeName: “”,  
    7.         places: []  
    8.     };  
    9.   
    10.     placeNameChangedHandler = val => {  
    11.         this.setState({  
    12.             placeName: val  
    13.         });  
    14.     };  
    15.   
    16.     placeSubmitHandler = () => {  
    17.         alert(“button clicked”)  
    18.     };  
    19.   
    20.     render() {  
    21.         return (  
    22.             <View style={styles.container}>  
    23.                 <TextInput  
    24.                         placeholder=”An awesome place”  
    25.                         onChangeText={this.placeNameChangedHandler}  
    26.                         style={styles.placeInput}  
    27.                 />  
    28.                 <Button  
    29.                         title=”Button”  
    30.                         onPress={this.placeSubmitHandler}  
    31.                 />  
    32.             </View>  
    33.         );  
    34.     }  
    35. }  
    36.   
    37. const styles = StyleSheet.create({  
    38.     container: {  
    39.         flex: 1,  
    40.         padding: 26,  
    41.         backgroundColor: “#fff”,  
    42.         justifyContent: “flex-start”  
    43.     }  
    44. });  

    Output:

    React Native Positioning Element with Flex

    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.

    1. import React, { Component } from “react”;  
    2. import { StyleSheet, View, TextInput, Button } from “react-native”;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         placeName: “”,  
    7.         places: []  
    8.     };  
    9.   
    10.     placeNameChangedHandler = val => {  
    11.         this.setState({  
    12.             placeName: val  
    13.         });  
    14.     };  
    15.   
    16.     placeSubmitHandler = () => {  
    17.         alert(“button clicked”)  
    18.     };  
    19.   
    20.     render() {  
    21.         return (  
    22.             <View style={styles.container}>  
    23.                 <View style={styles.innerContainer}>  
    24.                     <TextInput  
    25.                             placeholder=”An awesome place”  
    26.                             onChangeText={this.placeNameChangedHandler}  
    27.                     />  
    28.                     <Button  
    29.                             title=”Button”  
    30.                             onPress={this.placeSubmitHandler}  
    31.                     />  
    32.                 </View>  
    33.             </View>  
    34.         );  
    35.     }  
    36. }  
    37.   
    38. const styles = StyleSheet.create({  
    39.     container: {  
    40.         flex: 1,  
    41.         padding: 26,  
    42.         backgroundColor: “#fff”,  
    43.         justifyContent: “flex-start”  
    44.     },  
    45.     innerContainer:{  
    46.         flex: 1,  
    47.         flexDirection: “row”  
    48.     }  
    49. });  

    Output:

    React Native Positioning Element with Flex

    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.

    1. import React, { Component } from “react”;  
    2. import { StyleSheet, View, TextInput, Button } from “react-native”;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         placeName: “”,  
    7.         places: []  
    8.     };  
    9.   
    10.     placeNameChangedHandler = val => {  
    11.         this.setState({  
    12.             placeName: val  
    13.         });  
    14.     };  
    15.   
    16.     placeSubmitHandler = () => {  
    17.         alert(“button clicked”)  
    18.     };  
    19.   
    20.     render() {  
    21.         return (  
    22.             <View style={styles.container}>  
    23.                 <View style={styles.innerContainer}>  
    24.                     <TextInput  
    25.                             placeholder=”An awesome place”  
    26.                             onChangeText={this.placeNameChangedHandler}  
    27.                             style={styles.textStyle}  
    28.                     />  
    29.                     <Button  
    30.                             title=”Button”  
    31.                             onPress={this.placeSubmitHandler}  
    32.                     />  
    33.                 </View>  
    34.             </View>  
    35.         );  
    36.     }  
    37. }  
    38.   
    39. const styles = StyleSheet.create({  
    40.     container: {  
    41.         flex: 1,  
    42.         padding: 26,  
    43.         backgroundColor: “#fff”,  
    44.         justifyContent: “flex-start”  
    45.     },  
    46.     innerContainer:{  
    47.        // flex: 1,  
    48.         width: “100%”,  
    49.         flexDirection: “row”,  
    50.         justifyContent: “space-between”,  
    51.         alignItems: “center”  
    52.     },  
    53.     textStyle:{  
    54.         width: “70%”,  
    55.         backgroundColor: “gray”,  
    56.     },  
    57.     buttonStyle:{  
    58.         width: “30%”,  
    59.     }  
    60. });  

    Output:

    React Native Positioning Element with Flex
  • React Native Layout and Flexbox

    React Native Flexbox is an algorithm to specify the layout of component’s children. It provides a consistent layout on different screen sizes.

    Property of Flexbox

    Flexbox provides three main properties to achieve the desired layout. These properties are: flexDirectionjustifyContent, and alignItems.

    PropertyValuesDescription
    flexDirection‘column’, ‘row’Used to align its elements vertically or horizontally.
    justifyContent‘center’, ‘flex-start’, ‘flex-end’, ‘space-around’, ‘space-between’Used to distribute the elements inside the container.
    alignItems‘center’, ‘flex-start’, ‘flex-end’, ‘stretched’Used to distribute the element inside the container along the secondary axis (opposite to flexDirection).

    React Native Flex Direction

    The flexDirection adds the style to the component in a primary axis of its layout. It has a property row and column to organize children horizontally and vertically respectively. The default flexDirection is a column.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet,View } from ‘react-native’;  
    3.   
    4. export default class FlexDirectionBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.         flex: 1,  
    18.         flexDirection: ‘row’,// set elements horizontally, try column.  
    19.     },  
    20.     powderblue:{  
    21.         width: 60,  
    22.         height: 60,  
    23.         backgroundColor: ‘powderblue’,  
    24.     },  
    25.     skyblue:{  
    26.         width: 60,  
    27.         height: 60,  
    28.         backgroundColor: ‘skyblue’,  
    29.     },  
    30.     steelblue:{  
    31.         width: 60,  
    32.         height: 60,  
    33.         backgroundColor: ‘steelblue’,  
    34.     }  
    35. })  

    Output

    React Native Layout and Flexbox

    React Native Justify Content

    The justifyContent determines the distribution of children component along the primary axis. The children component are distributed at the start, end, center, or space evenly.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet,View } from ‘react-native’;  
    3.   
    4. export default class JustifyContentBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.         flex: 1,  
    18.         flexDirection: ‘column’, // set elements horizontally`.  
    19.         justifyContent: ‘center’,  
    20.   
    21.     },  
    22.     powderblue:{  
    23.         width: 60,  
    24.         height: 60,  
    25.         backgroundColor: ‘powderblue’  
    26.     },  
    27.     skyblue:{  
    28.         width: 60,  
    29.         height: 60,  
    30.         backgroundColor: ‘skyblue’,  
    31.     },  
    32.     steelblue:{  
    33.         width: 60,  
    34.         height: 60,  
    35.         backgroundColor: ‘steelblue’,  
    36.     }  
    37. })  

    Output

    React Native Layout and Flexbox

    React Native Align Items

    The alignItems determine the alignment of children component along the secondary axis. If the primary axis is a column, then the secondary is a row, and when a primary axis is a row, then the secondary is a column. Using the alignItems, the children are aligned at start, end, center, or stretched.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet,View } from ‘react-native’;  
    3.   
    4. export default class AlignItemsBasics extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.         flex: 1,  
    18.         flexDirection: ‘column’, // set elements horizontally`.  
    19.         justifyContent: ‘center’,  
    20.         alignItems: ‘stretch’,  
    21.     },  
    22.     powderblue:{  
    23.         width: 60,  
    24.         height: 60,  
    25.         backgroundColor: ‘powderblue’  
    26.     },  
    27.     skyblue:{  
    28.         width: 60,  
    29.         height: 60,  
    30.         backgroundColor: ‘skyblue’,  
    31.     },  
    32.     steelblue:{  
    33.         /*width: 60,*/  
    34.         height: 60,  
    35.         backgroundColor: ‘steelblue’,  
    36.     }  
    37. })  

    Output

    React Native Layout and Flexbox
  • 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

    PropTypeRequiredDescription
    onPressfunctionyesCall the handler when user clicks the button.
    titlestringyesDisplay the text inside the button.
    accessibilityLabelstringnoDisplay the text for blindness accessibility features.
    colorColornoSet the background color of the Android button or set the color of iOS text.
    disabledboolnoIt disables all interactions for this component, if true.
    textIDstringnoUsed to locate this view in end-to-end tests.
    hasTVPreferredFocusboolnoIt preferred TV focus work only for Apple TV.

    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 previous article Positioning Element with Flex, we learned how to position elements in View.

    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.

    1. import React, { Component } from ‘react’;  
    2. import { Alert, AppRegistry, Button, StyleSheet, View } from ‘react-native’;  
    3.   
    4. export default class ButtonBasics extends Component {  
    5.     onPressButton() {  
    6.         Alert.alert(‘You clicked the button!’)  
    7.     }  
    8.   
    9.     render() {  
    10.         return (  
    11.             <View style={styles.container}>  
    12.                 <View style={styles.buttonContainer}>  
    13.                     <Button  
    14.                         onPress={this.onPressButton}  
    15.                         title=”Press Me”  
    16.                     />  
    17.                 </View>  
    18.                 <View style={styles.buttonContainer}>  
    19.                     <Button  
    20.                         onPress={this.onPressButton}  
    21.                         title=”Press Me”  
    22.                         color=”#009933″  
    23.                     />  
    24.                 </View>  
    25.                 <View style={styles.multiButtonContainer}>  
    26.                     <Button  
    27.                         onPress={this.onPressButton}  
    28.                         title=”A disabled button”  
    29.                         disabled={true}  
    30.                     />  
    31.                     <Button  
    32.                         onPress={this.onPressButton}  
    33.                         title=”OK!”  
    34.                         color=”#009933″  
    35.                     />  
    36.                 </View>  
    37.             </View>  
    38.         );  
    39.     }  
    40. }  
    41.   
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         justifyContent: ‘center’,  
    46.     },  
    47.     buttonContainer: {  
    48.         margin: 20  
    49.     },  
    50.     multiButtonContainer: {  
    51.         margin: 20,  
    52.         flexDirection: ‘row’,  
    53.         justifyContent: ‘space-between’  
    54.     }  
    55. })  

    Output:

    React Native Button
    React Native Button
  • React Native Height and Width

    The height and width determine the size of component on the screen. There are two different ways to set the height and width of component: Fixed Dimensions and Flex Dimensions.

    Fixed Dimensions

    Using fixed height and fixed width in style is the simplest way to set the dimension of the component. The dimensions of React Native component are unit-less, and they represent density-independent pixels.

    Setting the dimension of component with fixed size is common and exactly the same size, regardless of screen dimensions.

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet, View } from ‘react-native’;  
    3.   
    4. export default class HeightWidth extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     powderblue:{  
    17.         width: 100, height: 100, backgroundColor: ‘powderblue’  
    18.     },  
    19.     skyblue:{  
    20.         width: 200, height: 200, backgroundColor: ‘skyblue’  
    21.     },  
    22.     steelblue:{  
    23.         height: 300, backgroundColor: ‘steelblue’  
    24.     },  
    25. })  

    Output

    React Native Height and Width

    Flex Dimensions

    The flex property styles the component to expand and shrink it dynamically according to available space. Setting flex: 1 will fill all the available space to the component, and shared evenly among the other components of same as the parent. Higher the flex value, occupy component higher ratio of space compared to its siblings.

    1.  import React, { Component } from ‘react’;  
    2. import { StyleSheet, View } from ‘react-native’;  
    3.   
    4. export default class HeightWidth extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View style={styles.container}>  
    8.                 <View style={styles.powderblue} />  
    9.                 <View style={styles.skyblue} />  
    10.                 <View style={styles.steelblue} />  
    11.             </View>  
    12.         );  
    13.     }  
    14. }  
    15. const styles = StyleSheet.create({  
    16.     container:{  
    17.       flex:1  
    18.     },  
    19.     powderblue:{  
    20.         flex:1,  
    21.         backgroundColor: ‘powderblue’,  
    22.     },  
    23.     skyblue:{  
    24.         flex:2,  
    25.         backgroundColor: ‘skyblue’,  
    26.     },  
    27.     steelblue:{  
    28.         flex:3,  
    29.         backgroundColor: ‘steelblue’,  
    30.     },  
    31. })  

    Output

    React Native Height and Width
  • React Native Style

    React Native simply uses JavaScript for styling our core components. We don’t require any special language or syntax for defining styles. All the core components use a prop (property) named style. The style names and values are similar to CSS that works for the web. There is the only difference in the way of writing names using camel casing, e.g fontSize rather than font-size.

    The style prop is a plain old JavaScript object which is the simplest way for styling our code.

    There are different ways to design our component, by using inline style and by using StyleSheet.create. As the component increases in complexity, it is better to use StyleSheet.create to define several styles in one place.

    React Native style Example 1

    In this example, we will use both inline style as well as StyleSheet.create. Inline styles are applied at where the components are created.

    App.js

    1.  import React, { Component } from ‘react’;  
    2. import { AppRegistry, StyleSheet, Text, View } from ‘react-native’;  
    3.   
    4. export default class ImplementingStyle extends Component {  
    5.     render() {  
    6.         return (  
    7.             <View>  
    8.                 <Text style={{ backgroundColor: ‘#a7a6a9’, color: ‘yellow’, fontSize: 20 }}>this is inline style</Text>  
    9.                 <Text style={styles.green}>just green</Text>  
    10.                 <Text style={styles.biggray}>just biggray</Text>  
    11.                 <Text style={[styles.biggray, styles.green]}>biggray, then green</Text>  
    12.                 <Text style={[styles.green, styles.biggray]}>green, then biggray</Text>  
    13.             </View>  
    14.         );  
    15.     }  
    16. }  
    17. const styles = StyleSheet.create({  
    18.     biggray: {  
    19.         color: ‘gray’,  
    20.         fontWeight: ‘bold’,  
    21.         fontSize: 30,  
    22.     },  
    23.     green: {  
    24.         color: ‘green’,  
    25.     },  
    26. });  

    Output

    React Native Style

    React Native style Example 2

    We can also use the external JavaScript file to style our application. In this example, we create external JS file and import it into our App.js file.

    StyleComponent.js

    1. import React, { Component } from ‘react’  
    2. import { Text, View, StyleSheet } from ‘react-native’  
    3.   
    4. const StyleComponent = (props) => {  
    5.     return (  
    6.         <View>  
    7.             <Text style = {styles.myState}>  
    8.                 {props.myState}  
    9.             </Text>  
    10.         </View>  
    11.     )  
    12. }  
    13. export default StyleComponent  
    14.   
    15. const styles = StyleSheet.create ({  
    16.     myState: {  
    17.         marginTop: 20,  
    18.         textAlign: ‘center’,  
    19.         color: ‘green’,  
    20.         fontWeight: ‘bold’,  
    21.         fontSize: 20  
    22.     }  
    23. })  

    App.js

    1.  import React from ‘react’;  
    2. import { StyleSheet, Text, View } from ‘react-native’;  
    3. import StyleComponent from ‘./StyleComponent’  
    4.   
    5. export default class App extends React.Component {  
    6.     state = {  
    7.         myState: ‘This is my state, style through external style’  
    8.     }  
    9.     render() {  
    10.         return (  
    11.             <View>  
    12.                 <StyleComponent myState = {this.state.myState}/>  
    13.             </View>  
    14.         );  
    15.     }  
    16. }  

    Output

    React Native Style
  • React Native Props

    The properties of React Native components are simply pronounced as props. In React Native, most of the components can be customized at the time of their creation with different parameters. These parameters are known as props. They are immutable, and they cannot be changed.

    One of the examples of props is a source property if Image component which controls the image is displayed over the device screen.

    React Native Default custom Props

    1.  import React, { Component } from ‘react’;  
    2. import {  
    3.   Platform,  
    4.   StyleSheet,  
    5.   Image,  
    6.   Text,  
    7.   View  
    8. } from ‘react-native’;  
    9.   
    10.   
    11. export default class App extends Component<{}> {  
    12.   render() {  
    13.     let imagePath = { uri: ‘https://facebook.github.io/react-native/img/header_logo.png’};  
    14.     return (  
    15.         <View style={styles.container}>  
    16.           <Text style={styles.welcome}>Welcome to React Native!</Text>  
    17.           <Image source={imagePath} style={{width: 250, height: 250}} />  
    18.         </View>  
    19.     );  
    20.   }  
    21. }  
    22.   
    23. const styles = StyleSheet.create({  
    24.   container: {  
    25.     flex: 1,  
    26.     justifyContent: ‘center’,  
    27.     alignItems: ‘center’,  
    28.     backgroundColor: ‘#a7a6a9’,  
    29.   },  
    30.   welcome: {  
    31.     fontSize: 30,  
    32.     textAlign: ‘center’,  
    33.     margin: 20,  
    34.   }  
    35. });  

    Output:

    React Native Props

    Using props in our own Component

    We can also use props in our components. A single component can be used in many different places in the app by making slightly different properties in each place. To implement the props in our component, this.props is applied followed by the property.

    For example, one of the basic React Native components is Text. When we create a Text component, we can use a prop “name” as props to control its appearance. We also apply the StyleSheet to the component which is used as our component.

    App.js

    1.  import React, { Component } from ‘react’;  
    2. import { StyleSheet, Text, View } from ‘react-native’;  
    3.   
    4. class ChildClass extends Component {  
    5.   render() {  
    6.     return (  
    7.         <View style={{alignItems: ‘center’}}>  
    8.           <Text style={styles.welcome}>Hello {this.props.name}!</Text>  
    9.         </View>  
    10.     );  
    11.   }  
    12. }  
    13.   
    14. export default class ParentsClass extends Component {  
    15.   render() {  
    16.     return (  
    17.         <View style={{alignItems: ‘center’}}>  
    18.           <ChildClass name=’Ashu’ />  
    19.           <ChildClass name=’Aman’ />  
    20.           <ChildClass name=’Max’ />  
    21.         </View>  
    22.     );  
    23.   }  
    24. }  
    25. const styles = StyleSheet.create({  
    26.    welcome: {  
    27.     fontSize: 30,  
    28.   }  
    29. });  
    30.   
    31. // skip this line if using Create React Native App  
    32. //AppRegistry.registerComponent(‘MyReactNativeApp’, () => ParentsClass);  

    Output:

    React Native Props
  • React Native State

    There are two types of data state and props in React Native which control the component. The component that uses the state is mutable. They can be changed later on if required. The props component is immutable, and it is fixed throughout the lifetime.

    The state is generally initialized in constructor and then call setState when we want to change it.

    React Native state Example 1

    In this example, we create a Text component with state data. The content of Text component will be updated by clicking on it. The event onPress call the setState, and it updates the state “myState” text.

    1.  import React, {Component} from ‘react’;  
    2. import { Text, View } from ‘react-native’;  
    3.   
    4. export default class App extends Component {  
    5.     state = {  
    6.         myState: ‘This is a text component, created using state data. It will change or updated on clicking it.’  
    7.     }  
    8.     updateState = () => this.setState({myState: ‘The state is updated’})  
    9.     render() {  
    10.         return (  
    11.             <View>  
    12.                 <Text onPress={this.updateState}> {this.state.myState} </Text>  
    13.             </View>  
    14.         );  
    15.     }  
    16. }  

    Output

    React Native State
    React Native State

    React Native state Example 2

    Let’s create another example of state data in which we interchange the Text value “Show” and “Hide” to show and hide the input password.

    Create three state variables that will be changed by clicking the Text component defined as a state. Clicking the Text component calls the handleToggle function, and the current state of Boolean variable “isPasswordVisible” is assigned in it. Here, if the condition checks the value of “isPasswordVisible” and proceeds accordingly.

    1.  import React, { Component } from ‘react’;  
    2. import {StyleSheet,Text,View,TextInput,TouchableOpacity} from ‘react-native’;  
    3.   
    4. export default class App extends Component {  
    5.     state: {  
    6.         password: string,  
    7.         isPasswordVisible: boolean,  
    8.         toggleText: string,  
    9.     }  
    10.     constructor(props: Props) {  
    11.         super(props);  
    12.         this.state = {  
    13.             password: ”,  
    14.             isPasswordVisible: true,  
    15.             toggleText: ‘Show’,  
    16.         };  
    17.     }  
    18.     handleToggle = () => {  
    19.         const { isPasswordVisible } = this.state;  
    20.         if (isPasswordVisible) {  
    21.             this.setState({ isPasswordVisible: false });  
    22.             this.setState({ toggleText: ‘Hide’ });  
    23.         } else {  
    24.             this.setState({ isPasswordVisible: true });  
    25.             this.setState({ toggleText: ‘Show’ });  
    26.         }  
    27.     };  
    28.     render() {  
    29.         return (  
    30.             <View style={styles.container}>  
    31.                 <TextInput  
    32.                     secureTextEntry={this.state.isPasswordVisible}  
    33.                     style={{ width: 400, height: 50, backgroundColor: ‘#a7a6a9’, color: ‘white’, fontSize: 20 }}  
    34.                 />  
    35.                 <TouchableOpacity onPress={this.handleToggle}>  
    36.                     <Text  style={{fontSize: 20}}>{this.state.toggleText}</Text>  
    37.                 </TouchableOpacity>  
    38.             </View>  
    39.         );  
    40.     }  
    41. }  
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         justifyContent: ‘center’,  
    46.         alignItems: ‘center’,  
    47.     }  
    48. });  

    Output

    React Native State
    React Native State