Author: saqibkhan

  • React Native Vector Icons

    React Native Vector Icons are the most popular custom icons of NPM GitHub library. It has more than 3K (3000) icons collection in it. All these icons are free to use. The React Native Vector icons come with complete customization such as icon size, icon color, and it also supports multiple styling.

    Following are the list of icons category available in React Native Vector Icons. You can also visit at https://oblador.github.io/react-native-vector-icons/ for these icons.

    • AntDesign by AntFinance (297 icons)
    • Entypo by Daniel Bruce (411 icons)
    • EvilIcons by Alexander Madyankin & Roman Shamin (v1.10.1, 70 icons)
    • Feather by Cole Bemis & Contributors (v4.21.0, 279 icons)
    • FontAwesome by Dave Gandy (v4.7.0, 675 icons)
    • FontAwesome 5 by Fonticons, Inc. (v5.7.0, 1500 (free) 5082 (pro) icons)
    • Fontisto by Kenan Gündo?an (v3.0.4, 615 icons)
    • Foundation by ZURB, Inc. (v3.0, 283 icons)
    • Ionicons by Ben Sperry (v4.2.4, 696 icons)
    • MaterialIcons by Google, Inc. (v3.0.1, 932 icons)
    • MaterialCommunityIcons by MaterialDesignIcons.com (v3.6.95, 3695 icons)
    • Octicons by Github, Inc. (v8.4.1, 184 icons)
    • Zocial by Sam Collins (v1.0, 100 icons)
    • SimpleLineIcons by Sabbir & Contributors (v2.4.1, 189 icons)

    Installation of React Native Vector Icons

    1. Open your react native project folder in command prompt and execute the below code:

    1. npm install react-native-vector-icons –save  
    React Native Vector Icons

    After successful execution of the above code, it adds the react-native-vector-icons library.

    React Native Vector Icons

    2. Open your_react_native_project->android -> app -> build.gradle file and put below code of line inside it.

    1. apply from: “../../node_modules/react-native-vector-icons/fonts.gradle”  

    3. Again open your_react_native_project -> android -> app -> build.gradle file and put the below code inside the dependency block.

    1. implementation project(‘:react-native-vector-icons’)  

    your_react_native_project->android -> app -> build.gradle

    After adding the above code, the build.gradle file looks like as:

    1. apply plugin: “com.android.application”  
    2. apply from: “../../node_modules/react-native-vector-icons/fonts.gradle”  
    3. import com.android.build.OutputFile  
    4.   
    5. project.ext.react = [  
    6.     entryFile: “index.js”  
    7. ]  
    8.   
    9. apply from: “../../node_modules/react-native/react.gradle”  
    10.   
    11. def enableSeparateBuildPerCPUArchitecture = false  
    12.   
    13. /** 
    14.  * Run Proguard to shrink the Java bytecode in release builds. 
    15.  */  
    16. def enableProguardInReleaseBuilds = false  
    17.   
    18. android {  
    19.     compileSdkVersion rootProject.ext.compileSdkVersion  
    20.     buildToolsVersion rootProject.ext.buildToolsVersion  
    21.   
    22.     defaultConfig {  
    23.         applicationId “com.vectoricons”  
    24.         minSdkVersion rootProject.ext.minSdkVersion  
    25.         targetSdkVersion rootProject.ext.targetSdkVersion  
    26.         versionCode 1  
    27.         versionName “1.0”  
    28.         ndk {  
    29.             abiFilters “armeabi-v7a”, “x86”  
    30.         }  
    31.     }  
    32.     splits {  
    33.         abi {  
    34.             reset()  
    35.             enable enableSeparateBuildPerCPUArchitecture  
    36.             universalApk false  // If true, also generate a universal APK  
    37.             include “armeabi-v7a”, “x86”  
    38.         }  
    39.     }  
    40.     buildTypes {  
    41.         release {  
    42.             minifyEnabled enableProguardInReleaseBuilds  
    43.             proguardFiles getDefaultProguardFile(“proguard-android.txt”), “proguard-rules.pro”  
    44.         }  
    45.     }  
    46.     // applicationVariants are e.g. debug, release  
    47.     applicationVariants.all { variant ->  
    48.         variant.outputs.each { output ->  
    49.             // For each separate APK per architecture, set a unique version code as described here:  
    50.             // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits  
    51.             def versionCodes = [“armeabi-v7a”:1, “x86”:2]  
    52.             def abi = output.getFilter(OutputFile.ABI)  
    53.             if (abi != null) {  // null for the universal-debug, universal-release variants  
    54.                 output.versionCodeOverride =  
    55.                         versionCodes.get(abi) * 1048576 + defaultConfig.versionCode  
    56.             }  
    57.         }  
    58.     }  
    59. }  
    60.   
    61. dependencies {  
    62.     compile project(‘:react-native-vector-icons’)  
    63.     implementation fileTree(dir: “libs”, include: [“*.jar”])  
    64.     implementation “com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}”  
    65.     implementation “com.facebook.react:react-native:+”  // From node_modules  
    66.     implementation project(‘:react-native-vector-icons’)  
    67. }  
    68.   
    69. // Run this once to be able to run the application with BUCK  
    70. // puts all compile dependencies into folder libs for BUCK to use  
    71. task copyDownloadableDepsToLibs(type: Copy) {  
    72.     from configurations.compile  
    73.     into ‘libs’  
    74. }  

    4. Open your_react_native_project-> android-> settings.gradle file and add the below code:

    1. include ‘:react-native-vector-icons’  
    2. project(‘:react-native-vector-icons’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-vector-icons/android’)  

    your_react_native_project-> android-> settings.gradle

    1. rootProject.name = ‘VectorIcons’  
    2. include ‘:react-native-vector-icons’  
    3. project(‘:react-native-vector-icons’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-vector-icons/android’)  
    4. include ‘:app’  

    5. Open your_react_native_project -> android -> app -> src -> main -> java-> com-> your_project_name -> MainApplication.java file and import vector icons package using below line of code.

    1. import com.oblador.vectoricons.VectorIconsPackage;  

    6. In the MainApplication.java file, call the react native vector icons below package name inside the return Arrays.asList()block.

    1. new VectorIconsPackage()  

    MainApplication.java

    1. package com.vectoricons;  
    2. import android.app.Application;  
    3. import com.facebook.react.ReactApplication;  
    4. import com.facebook.react.ReactNativeHost;  
    5. import com.facebook.react.ReactPackage;  
    6. import com.facebook.react.shell.MainReactPackage;  
    7. import com.facebook.soloader.SoLoader;  
    8. import com.oblador.vectoricons.VectorIconsPackage;  
    9. import java.util.Arrays;  
    10. import java.util.List;  
    11.   
    12. public class MainApplication extends Application implements ReactApplication {  
    13.   
    14.   private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {  
    15.     @Override  
    16.     public boolean getUseDeveloperSupport() {  
    17.       return BuildConfig.DEBUG;  
    18.     }  
    19.   
    20.     @Override  
    21.     protected List<ReactPackage> getPackages() {  
    22.       return Arrays.<ReactPackage>asList(  
    23.           new MainReactPackage(),  
    24.           new VectorIconsPackage()  
    25.       );  
    26.     }  
    27.   
    28.     @Override  
    29.     protected String getJSMainModuleName() {  
    30.       return “index”;  
    31.     }  
    32.   };  
    33.   
    34.   @Override  
    35.   public ReactNativeHost getReactNativeHost() {  
    36.     return mReactNativeHost;  
    37.   }  
    38.   @Override  
    39.   public void onCreate() {  
    40.     super.onCreate();  
    41.     SoLoader.init(this/* native exopackage */ false);  
    42.   }  
    43. }  

    Linking of Dependency

    After installing the above code, we need to link it with our project.

    1. react-native link  
    React Native Vector Icons

    In the App.js file, create two constant named as facebook_button and twitter_button inside the render block. We call these constant directly into the TouchableOpacity component. The props of Icon.Button are given below:

    PropsDescription
    name=” “In this prop, we pass the name of the icon.
    backgroundColor=” “It is used to set the color of the button.
    size={}It sets the size of the button.
    onPress={}It reprsents the onPress event on button.
    colorIt sets the color of Text and Icon.

    Create two another constant of Icon named as android_icon and music_icon inside render block.

    PropsDescription
    name=” “In this prop, we pass the name of the icon.
    size={}It sets the size of Icon.
    color=” “It sets the color of the Icon.
    onPress={}It is the onPress event on button.

    App.js

    1. /** 
    2.  * Sample React Native App 
    3.  * https://github.com/facebook/react-native 
    4.  * 
    5.  * @format 
    6.  * @flow 
    7.  */  
    8.   
    9. import React, {Component} from ‘react’;  
    10. import {Platform, StyleSheet, Text, View, TouchableOpacity, Alert} from ‘react-native’;  
    11. import Icon from ‘react-native-vector-icons/FontAwesome’;  
    12.   
    13. const instructions = Platform.select({  
    14.   ios: ‘Press Cmd+R to reload,\n’ + ‘Cmd+D or shake for dev menu’,  
    15.   android:  
    16.     ‘Double tap R on your keyboard to reload,\n’ +  
    17.     ‘Shake or press menu button for dev menu’,  
    18. });  
    19.   
    20. type Props = {};  
    21. export default class App extends Component<Props> {  
    22.   render() {  
    23.       const facebook_button = (  
    24.         <Icon.Button name=”facebook” backgroundColor=”#3b5998″ size={20} onPress={()=>{Alert.alert(“Facebook Button Clicked”)}}>  
    25.           <Text style={{fontFamily: ‘Arial’, fontSize: 15, color: ‘#fff’}}>Login with Facebook</Text>  
    26.         </Icon.Button>  
    27.       );  
    28.       
    29.       const twitter_button = (  
    30.        <Icon.Button name=”twitter” backgroundColor=”#51aaf0″ size={20} onPress={()=>{Alert.alert(“Twitter Button Clicked”)}}>  
    31.          <Text style={{fontFamily: ‘Arial’, fontSize: 15, color: ‘#fff’}}>Follow Us on Twitter</Text>  
    32.        </Icon.Button>  
    33.       );  
    34.   
    35.       const android_icon = (  
    36.        <Icon name=”android” size={60} color=”#007c00″ onPress={()=>{Alert.alert(“Android Icon Clicked”)}} />  
    37.       );  
    38.    
    39.       const music_icon = (  
    40.        <Icon name=”music” size={60} color=”#fb3742″ onPress={()=>{Alert.alert(“Music Icon Clicked”)}} />  
    41.       );  
    42.   
    43.     return (  
    44.       <View style={styles.MainContainer}>  
    45.           <TouchableOpacity>  
    46.             {facebook_button}  
    47.          </TouchableOpacity>  
    48.     
    49.         <TouchableOpacity style={{marginTop: 10}}>  
    50.            {twitter_button}  
    51.          </TouchableOpacity>  
    52.    
    53.    
    54.         <TouchableOpacity style={{marginTop: 10}}>  
    55.            {android_icon}  
    56.          </TouchableOpacity>  
    57.    
    58.         <TouchableOpacity style={{marginTop: 10}}>  
    59.           {music_icon}  
    60.         </TouchableOpacity>  
    61.       </View>  
    62.    
    63.     );  
    64.    
    65.   }  
    66. }  
    67. const styles = StyleSheet.create({  
    68.   MainContainer: {  
    69.     flex: 1,  
    70.     justifyContent: ‘center’,  
    71.     alignItems: ‘center’,  
    72.     backgroundColor: ‘#F5FCFF’,  
    73.     padding: 20  
    74.   }  
    75. });  

    Output:

    React Native Vector Icons
    React Native Vector Icons
  • React Native Modal

    The React Native Modal is a type of View component which is used to present the content above an enclosing view. There are three different types of options (slide, fade and none) available in a modal that decides how the modal will show inside the react native app.

    The Modal shows above the screen covers all the application area. To use the Modal component in our application, we need to import Modal from the react-native library.

    Modal Props

    PropsDescription
    visibleThis prop determines whether your modal is visible.
    supportedOritentionsIt allow for rotating the modal in any of the specified orientations (portrait, portrait-upside-down, landscape, landscape-left, landscape-right).
    onRequestCloseThis is a callback prop which is called when the user taps on the hardware back button on Android or the menu button on Apple TV.
    onShowThis allows passing a function which will show when the modal once visible.
    transparentIt determines whether the modal will cover the entire view. Setting it to “true” renders the modal over the transparent background.
    animationTypeIt controls how the modal animates. There are three types of animated props available:
    slide: It slides the modal from the bottom.
    fade: It fades into the view.
    none: It appears the model without any animation.
    hardwareAcceleratedIt controls whether to force hardware acceleration for the underlying window.
    onDismissThis prop passes a function that will be called once the modal has been dismissed.
    onOrientationChangeThis props is called when the orientation changes while the modal is being displayed. The type of orientation is “portrait” or “landscape”.
    presentationStyleIt controls the appearance of a model (fullScreen, pageSheet, fromSheet, overFullScreen) generally on the large devices.
    animatedThis prop is deprecated. Use the animatedType prop instead, which is discussed above.

    React Native Modal Example

    Let’s see an example of displaying a pop-up modal on clicking the button. Once we clicked the button, state variable isVisible sets to true and opens the Modal component.

    To implement the Modal component import Modal from the react-native library.

    App.js

    1. import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text, View, Button, Modal} from ‘react-native’;  
    3.   
    4. export default class App extends Component<Props> {  
    5.   state = {  
    6.     isVisible: false//state of modal default false  
    7.   }  
    8.   render() {  
    9.     return (  
    10.       <View style = {styles.container}>  
    11.         <Modal            
    12.           animationType = {“fade”}  
    13.           transparent = {false}  
    14.           visible = {this.state.isVisible}  
    15.           onRequestClose = {() =>{ console.log(“Modal has been closed.”) } }>  
    16.           {/*All views of Modal*/}  
    17.               <View style = {styles.modal}>  
    18.               <Text style = {styles.text}>Modal is open!</Text>  
    19.               <Button title=”Click To Close Modal” onPress = {() => {  
    20.                   this.setState({ isVisible:!this.state.isVisible})}}/>  
    21.           </View>  
    22.         </Modal>  
    23.         {/*Button will change state to true and view will re-render*/}  
    24.         <Button   
    25.            title=”Click To Open Modal”   
    26.            onPress = {() => {this.setState({ isVisible: true})}}  
    27.         />  
    28.       </View>  
    29.     );  
    30.   }  
    31. }  
    32.   
    33. const styles = StyleSheet.create({  
    34.   container: {  
    35.     flex: 1,  
    36.     alignItems: ‘center’,  
    37.     justifyContent: ‘center’,  
    38.     backgroundColor: ‘#ecf0f1’,  
    39.   },  
    40.   modal: {  
    41.   justifyContent: ‘center’,  
    42.   alignItems: ‘center’,   
    43.   backgroundColor : “#00BCD4”,   
    44.   height: 300 ,  
    45.   width: ‘80%’,  
    46.   borderRadius:10,  
    47.   borderWidth: 1,  
    48.   borderColor: ‘#fff’,    
    49.   marginTop: 80,  
    50.   marginLeft: 40,  
    51.    
    52.    },  
    53.    text: {  
    54.       color: ‘#3f2949’,  
    55.       marginTop: 10  
    56.    }  
    57. });  

    Output:

    React Native Modal
    React Native Modal
  • Google Maps

    Google map is used to locate an address, navigate, and search location in the mobile devices. The Google Maps shows the location (latitude and longitude) using dot Marker. In the react-native, Google Maps is easily integrated using react-native-maps npm library. To use Google Maps in our application, we need to authenticate the Google Maps API.

    1. Create the react-native project

    Create the react-native project and install the react-native-maps library using the below command

    1. npm install -save react-native-maps  
    React Native Google Map

    After successful execution of the above code, it installs the react-native-maps library, which can be seen in package.json file.

    React Native Google Map

    2. Generate Google Maps authentication API key from the Google Developer Console

    2.1 To use Google Maps in our application, we need to generate and authenticate the Google Maps API key. Login to https://console.developers.google.com/ with your google mail account and create a new project.

    React Native Google Map

    2.2 Now, click on API and Services -> Credentials -> Create credentials to create API credentials.

    React Native Google Map

    2.3 It will pop up your API key with message API key created.

    React Native Google Map

    2.4 To see an overview of your API key, click Google Maps -> Overview.

    React Native Google Map
    React Native Google Map

    2.5 Now, go to API Library and select Maps SDK for Android to enable the Map API.

    React Native Google Map
    React Native Google Map

    3. Open your project_name -> android -> setting.gradle file and add the below code:

    1. include ‘:react-native-maps’  
    2. project(‘:react-native-maps’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-maps/lib/android’)  

    4. Again open your project_name ->android -> build.gradle file and add the below code in dependencies block.

    1. implementation project(‘:react-native-maps’)  

    5. Go to project_name -> android ->app->src->main->java->com->project_name-> MainApplication.java and add the below code:

    1. import com.airbnb.android.react.maps.MapsPackage;  
    2. …  
    3. new MapsPackage()  

    MainApplication.java

    1. package com.maps;  
    2. import android.app.Application;  
    3. import com.facebook.react.ReactApplication;  
    4. import com.airbnb.android.react.maps.MapsPackage;  
    5. import com.facebook.react.ReactNativeHost;  
    6. import com.facebook.react.ReactPackage;  
    7. import com.facebook.react.shell.MainReactPackage;  
    8. import com.facebook.soloader.SoLoader;  
    9. import com.airbnb.android.react.maps.MapsPackage;  
    10. import java.util.Arrays;  
    11. import java.util.List;  
    12.   
    13. public class MainApplication extends Application implements ReactApplication {  
    14.   private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {  
    15.     @Override  
    16.     public boolean getUseDeveloperSupport() {  
    17.       return BuildConfig.DEBUG;  
    18.     }  
    19.     @Override  
    20.     protected List<ReactPackage> getPackages() {  
    21.       return Arrays.<ReactPackage>asList(  
    22.           new MainReactPackage(),  
    23.             new MapsPackage()  
    24.       );  
    25.     }  
    26.     @Override  
    27.     protected String getJSMainModuleName() {  
    28.       return “index”;  
    29.     }  
    30.   };  
    31.   @Override  
    32.   public ReactNativeHost getReactNativeHost() {  
    33.     return mReactNativeHost;  
    34.   }  
    35.   @Override  
    36.   public void onCreate() {  
    37.     super.onCreate();  
    38.     SoLoader.init(this/* native exopackage */ false);  
    39.   }  

    6. In your project_name -> android -> app -> src -> main ->AndroidManifest.xml file add the below code inside application tag.

    1. <meta-data  
    2. android:name=”com.google.android.geo.API_KEY”  
    3. android:value=”Your_Google_API_Key”/>  

    7. Import the MapView and Marker component from react-native-maps library in App.js file.

    MapView: It is used to display the MapView component in the project.

    Marker: It is used to show the red round mark to pinpoint the exact location in Google Maps.

    App.js

    1. import React, { Component } from ‘react’;  
    2. import { StyleSheet, View } from ‘react-native’;  
    3. import MapView from ‘react-native-maps’;  
    4. import { Marker } from ‘react-native-maps’;  
    5.   
    6. export default class App extends Component {  
    7.   render() {  
    8.     return (  
    9.       <View style={styles.MainContainer}>  
    10.   
    11.         <MapView  
    12.           style={styles.mapStyle}  
    13.           showsUserLocation={false}  
    14.           zoomEnabled={true}  
    15.           zoomControlEnabled={true}  
    16.           initialRegion={{  
    17.             latitude: 28.579660,   
    18.             longitude: 77.321110,  
    19.             latitudeDelta: 0.0922,  
    20.             longitudeDelta: 0.0421,  
    21.           }}>  
    22.   
    23.           <Marker  
    24.             coordinate={{ latitude: 28.579660, longitude: 77.321110 }}  
    25.             title={“JavaTpoint”}  
    26.             description={“Java Training Institute”}  
    27.           />  
    28.         </MapView>  
    29.           
    30.       </View>  
    31.     );  
    32.   }  
    33. }  
    34.   
    35. const styles = StyleSheet.create({  
    36.   MainContainer: {  
    37.     position: ‘absolute’,  
    38.     top: 0,  
    39.     left: 0,  
    40.     right: 0,  
    41.     bottom: 0,  
    42.     alignItems: ‘center’,  
    43.     justifyContent: ‘flex-end’,  
    44.   },  
    45.   mapStyle: {  
    46.     position: ‘absolute’,  
    47.     top: 0,  
    48.     left: 0,  
    49.     right: 0,  
    50.     bottom: 0,  
    51.   },  
    52. });  

    Output:

    React Native Google Map
    React Native Google Map
  • AsyncStorage Methods

    There are various methods of React Native AsyncStorage class which are described below:

    Methods

    setItem()

    1. static setItem(key: string, value: string, [callback]: ?(error: ?Error)=>void)  

    The setItem() sets the value for a key and invokes a callback upon compilation. It returns a Promise object.

    getItem()

    1. static getItem(key: string, [callback]: ?(error: ?Error, result: ?string)) =>void)  

    The getItem() fetches an item from a key and invokes a callback upon completion. It returns a Promise object.

    removeItem()

    1. static removeItem(key: string, [callback]: ?(error: ?Error) => void)  

    The removeItem() removes an item for a key and invokes a callback upon compilation. It returns a Promise object.

    mergeItem()

    1. static mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void)  

    The mergeItem() merges the existing key’s value with the input value and assuming both values are stringified JSON. It returns a Promise object.

    NOTE: This method is not supported by all the native implementations.

    clear()

    1. static clear([callback]: ?(error: ?Error) => void)  

    The clear() method erases all AsynchStorage from all clients, libraries, etc. It is suggested that don’t call this, instead of this you may use removeItem or multiRemove to clear only your app’s keys. It returns the Promise object.

    getAllKeys()

    1. static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)  

    It gets all the keys which are known to your app, for all callers, libraries, etc. It returns a Promise object.

    flushGetRequests()

    1. static flushGetRequests(): [object Object]  

    It flushes any pending request using a single batch call to get the data.

    multiGet()

    1. static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void)  

    This method allows you to batch fetching of items given in an array of key inputs. The callback method will be invoked with an array of corresponding key-value pairs found:

    1. multiGet([‘k1’, ‘k2’], cb) -> cb([[‘k1’, ‘val1’], [‘k2’, ‘val2’]])  

    The method returns a Promise object.

    multiSet()

    1. static multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)  

    This method is used as a batch operation to store multiple key-value pairs. After the completion of operations, you will get a single callback with any errors:

    1. multiSet([[‘k1’, ‘val1’], [‘k2’, ‘val2’]], cb);  

    The method returns a Promise object.

    multiRemove()

    1. static multiRemove(keys: Array<string>, [callback]: ?(errors: ?Array<Error>) => void)  

    This method calls the batch deletion of all keys in the key array. It returns a Promise object.

    multiMerge()

    1. static multiMerge(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)  

    It executes the batch of operation to merge existing and new values for a given set of keys. It assumes that the values are stringified JSON. It returns a Promise object.

  • AsyncStorage

    React Native AsyncStorage is a simple, unencrypted, asynchronous, persistent, storage system which stores the data globally in the app. It store data in the form of a key-value pair.

    React Native recommended to use abstraction on top of AsyncStorage instead of AsyncStorage directly as it operates globally.

    On iOS, AsyncStorage is approved by the native code. The iOS native code stores the small values in a serialized dictionary and the larger values in separate files.

    On Android, AsyncStorage will use either SQLite or RocksDB based on the availability.

    To use the AsyncStorage, import AsyncStorage library as:

    1. import {AsyncStorage} from ‘react-native’;  

    Persist Data:

    React Native AsyncStorage saves the data using setItem() method as:

    1. AsyncStorage.setItem(‘key’, ‘value’);  

    Example of persisting the single value:

    1. let name = “Michal”;  
    2. AsyncStorage.setItem(‘user’,name);  

    Example of persisting multiple values in an object:

    1. let obj = {  
    2.       name: ‘Michal’,  
    3.       email: ‘[email protected]’,  
    4.       city: ‘New York’,  
    5.     }  
    6. AsyncStorage.setItem(‘user’,JSON.stringify(obj));  

    Fetch Data:

    React Native AsyncStorage fetches the saved data using getItem() method as:

    1. await AsyncStorage.getItem(‘key’);  

    Example to fetch the single value:

    1. await AsyncStorage.getItem(‘user’);  

    Example to fetch value from an object:

    1. let user = await AsyncStorage.getItem(‘user’);  
    2. let parsed = JSON.parse(user);  
    3. alert(parsed.email);  

    React Native AsyncStorage Example 1

    In this example, we create the two TouchableOpacity components, one for saving the data and another for retrieving. From first TouchableOpacity component call the savaData() method to save data and from the second TouchableOpacity component call the displayData() method to fetch data.

    1. import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text,  
    3.   View,TouchableOpacity, AsyncStorage,  
    4. } from ‘react-native’;  
    5.   
    6. export default class App extends Component<Props> {  
    7.   saveData(){  
    8.     let name = “Michal”;  
    9.     AsyncStorage.setItem(‘user’,name);  
    10.   }  
    11.   displayData = async ()=>{  
    12.     try{  
    13.       let user = await AsyncStorage.getItem(‘user’);  
    14.       alert(user);  
    15.     }  
    16.     catch(error){  
    17.       alert(error)  
    18.     }  
    19.   }  
    20.   render() {  
    21.     return (  
    22.       <View style={styles.container}>  
    23.         <TouchableOpacity onPress ={this.saveData}>  
    24.           <Text>Click to save data</Text>  
    25.         </TouchableOpacity>    
    26.         <TouchableOpacity onPress ={this.displayData}>  
    27.           <Text>Click to display data</Text>  
    28.         </TouchableOpacity>   
    29.       </View>  
    30.     );  
    31.   }  
    32. }  
    33.   
    34. const styles = StyleSheet.create({  
    35.   container: {  
    36.     flex: 1,  
    37.     justifyContent: ‘center’,  
    38.     alignItems: ‘center’,  
    39.     backgroundColor: ‘#F5FCFF’,  
    40.   },  
    41. });  

    Output:

    React Native AsyncStorage
    React Native AsyncStorage

    React Native AsyncStorage Example 2

    In this example, we will save the multiple values in the form if JSON object using JSON.stringify(). The JSON.stringify() takes the JavaScript object and convert them into JSON string. On the other hand, JSON.parse() method is used to fetch the AsyncStorage data. This method takes the JSON string and converts it into a JavaScript object before they are returned.

    1. import React, {Component} from ‘react’;  
    2. import {Platform, StyleSheet, Text,  
    3.   View,TouchableOpacity, AsyncStorage,  
    4. } from ‘react-native’;  
    5.   
    6. export default class App extends Component<Props> {  
    7.   saveData(){  
    8.     /*let user = “Michal”;*/  
    9.     let obj = {  
    10.       name: ‘Michal’,  
    11.       email: ‘[email protected]’,  
    12.       city: ‘New York’,  
    13.     }  
    14.     /*AsyncStorage.setItem(‘user’,user);*/  
    15.     AsyncStorage.setItem(‘user’,JSON.stringify(obj));  
    16.   }  
    17.   displayData = async ()=>{  
    18.     try{  
    19.       let user = await AsyncStorage.getItem(‘user’);  
    20.       let parsed = JSON.parse(user);  
    21.       alert(parsed.email);  
    22.     }  
    23.     catch(error){  
    24.       alert(error)  
    25.     }  
    26.   }  
    27.   render() {  
    28.     return (  
    29.       <View style={styles.container}>  
    30.         <TouchableOpacity onPress ={this.saveData}>  
    31.           <Text>Click to save data</Text>  
    32.         </TouchableOpacity>    
    33.         <TouchableOpacity onPress ={this.displayData}>  
    34.           <Text>Click to display data</Text>  
    35.         </TouchableOpacity>   
    36.       </View>  
    37.     );  
    38.   }  
    39. }  
    40.   
    41. const styles = StyleSheet.create({  
    42.   container: {  
    43.     flex: 1,  
    44.     justifyContent: ‘center’,  
    45.     alignItems: ‘center’,  
    46.     backgroundColor: ‘#F5FCFF’,  
    47.   },  
    48. });  

    Output:

    React Native AsyncStorage
    React Native AsyncStorage
  • Drawer Navigation

    React Native Drawer Navigation is an UI panel which displays the app’s navigation menu. By default it is hidden when not in use, but it appears when user swipes a finger from the edge of the screen or when user touches at the top of drawer icon added at app bar.

    React Native Drawer Navigation imports the createDrawerNavigator from the react-navigation library.

    1. import { createDrawerNavigator } from ‘react-navigation’  

    It implements the createDrawerNavigator() to add the list of classes (screens).

    1. createDrawerNavigator(RouteConfigs, DrawerNavigatorConfig);  

    To open and close the drawer, use the following helper methods:

    1. this.props.navigation.openDrawer();  
    2. this.props.navigation.closeDrawer();  

    If you like to toggle your drawer then call the following method:

    1. this.props.navigation.toggleDrawer();  

    Each of the above methods openDrawer()closeDrawer(), and toggleDrawer() are simply dispatching actions as:

    1. this.props.navigation.dispatch(DrawerActions.openDrawer());  
    2. this.props.navigation.dispatch(DrawerActions.closeDrawer());  
    3. this.props.navigation.dispatch(DrawerActions.toggleDrawer());  

    Before creating the React Native drawer navigation, first go through the React Native Navigation where we discussed the react-navigation installation process.

    React Native Drawer Navigation Example

    Create two separate classes “DashboardScreen” and “WelcomeScreen” in the react native app to display on screen. Add these screens to createStackNavigator and add “md-menu” icon of ‘react-native-vector-icons/Ionicons‘ package. On pressing the menu icon, call navigation.openDrawer() method to open drawer.

    Now, import createDrawerNavigator from ‘react-navigation‘ package and implement createDrawerNavigator(). After that add the stack navigation screen over it.

    1. import React, { Component } from ‘react’;  
    2. import { View, Text, StyleSheet, Button } from ‘react-native’;  
    3. import Icon from ‘react-native-vector-icons/Ionicons’;  
    4.   
    5. import {  
    6.     createSwitchNavigator,  
    7.     createAppContainer,  
    8.     createDrawerNavigator,  
    9.     createStackNavigator  
    10. } from ‘react-navigation’;  
    11. export default class App extends Component {  
    12.     render() {  
    13.         return <AppContainer />;  
    14.     }  
    15. }  
    16.   
    17. class WelcomeScreen extends Component {  
    18.     static navigationOptions = {  
    19.          title: ‘Welcome’,  
    20.     };  
    21.     render() {  
    22.         return (  
    23.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    24.                 <Text>WelcomeScreen</Text>  
    25.                 <Button  
    26.                     title=”Go to DashboardScreen”  
    27.                     onPress={() => this.props.navigation.navigate(‘Dashboard’)}  
    28.                 />  
    29.             </View>  
    30.         );  
    31.     }  
    32. }  
    33.   
    34. class DashboardScreen extends Component {  
    35.     static navigationOptions = {  
    36.          title: ‘Dashboard’,  
    37.     };  
    38.   
    39.     render() {  
    40.         return (  
    41.             <View style={{ flex: 1, alignItems: ‘center’, justifyContent: ‘center’ }}>  
    42.                 <Text>DashboardScreen</Text>  
    43.             </View>  
    44.         );  
    45.     }  
    46. }  
    47. const DashboardStackNavigator = createStackNavigator(  
    48.     {  
    49.         DashboardNavigator: DashboardScreen  
    50.     },  
    51.     {  
    52.         defaultNavigationOptions: ({ navigation }) => {  
    53.         return {  
    54.             headerLeft: (  
    55.                 <Icon  
    56.                     style={{ paddingLeft: 10 }}  
    57.                     onPress={() => navigation.openDrawer()}  
    58.                     name=”md-menu”  
    59.                     size={30}  
    60.                 />  
    61.             )  
    62.         };  
    63.         }  
    64.     }  
    65. );  
    66.   
    67. const WelcomeStackNavigator = createStackNavigator(  
    68.     {  
    69.         WelcomeNavigator: WelcomeScreen  
    70.     },  
    71.     {  
    72.         defaultNavigationOptions: ({ navigation }) => {  
    73.             return {  
    74.                 headerLeft: (  
    75.                     <Icon  
    76.                         style={{ paddingLeft: 10 }}  
    77.                         onPress={() => navigation.openDrawer()}  
    78.                         name=”md-menu”  
    79.                         size={30}  
    80.                     />  
    81.                 )  
    82.             };  
    83.         }  
    84.     }  
    85. );  
    86. const AppDrawerNavigator = createDrawerNavigator({  
    87.     Dashboard: {  
    88.         screen: DashboardStackNavigator  
    89.     },  
    90.     Welcome: {  
    91.         screen: WelcomeStackNavigator  
    92.     },  
    93. });  
    94.   
    95. const AppSwitchNavigator = createSwitchNavigator({  
    96.     Dashboard: { screen: AppDrawerNavigator },  
    97.     Welcome: { screen: WelcomeScreen },  
    98.   
    99. });  
    100.   
    101. const AppContainer = createAppContainer(AppSwitchNavigator);  
    102.   
    103. const styles = StyleSheet.create({  
    104.     container: {  
    105.         flex: 1,  
    106.         alignItems: ‘center’,  
    107.         justifyContent: ‘center’  
    108.     }  
    109. });  

    Output:

    React Native Drawer Navigation
    React Native Drawer Navigation
    React Native Drawer Navigation
  • Top Tab Navigator(createMaterialTopTabNavigator)

    The material style createMaterialTopTabNavigator is used to create tab navigator on the top of the screen. It provides functionality to create and display multiple screens routers. These screens are switches between each other by tapping route or swiping horizontally. The tab screen components are mounted when they are focused.

    The createMaterialTopTabNavigator function of react-navigation library facilitates us to implement top tab navigator.

    1. createMaterialTopTabNavigator(RouteConfigs, TabNavigatorConfig);  

    React Native Top Tab Navigator Example

    Let’s create a top tab navigator with custom status bar and header section. In this example, we will create three different screens for “Home”, “Profile” and “Settings” router. Each router screens are created in separate files.

    React Native Top Tab Navigator

    The directory structure of the application

    Create a src directory in your route project. Inside the src directory create index.js file and two other directories lib and screens. In the screens directory, we place three screens file index.js (HomeScreen)profile.js (ProfileScreen), and settings.js (SettingsScreen). In the lib directory, we implement createMaterialTopTabNavigator to create top tab navigator.

    React Native Top Tab Navigator

    topNavigation/index.js

    Make the few changes in the topNavigation/index.js file (replace ‘./App’ with ‘./src’).

    1. import {AppRegistry} from ‘react-native’;  
    2. import App from ‘./src’;  
    3. import {name as appName} from ‘./app.json’;  
    4.   
    5. AppRegistry.registerComponent(appName, () => App);  

    Create the classes and import Icon from ‘react-native-vector-icons/Ionicons‘ package. Implement tabBarIcon and add Icon tag in it.

    src/screens/index.js

    1. import React, {Component} from ‘react’;  
    2. import {View,Text} from ‘react-native’;  
    3. import Icon from ‘react-native-vector-icons/Ionicons’;  
    4. export default class HomeScreen extends Component{  
    5.     render() {  
    6.         return(  
    7.             <View>  
    8.                 <Text>This is Home Screen</Text>  
    9.             </View>  
    10.         )  
    11.     }  
    12. }  
    13. HomeScreen.navigationOptions={  
    14.             tabBarIcon:({tintColor, focused})=>(  
    15.             <Icon  
    16.                 name={focused ? ‘ios-home’ : ‘md-home’}  
    17.                 color={tintColor}  
    18.                 size={25}  
    19.             />  
    20.         )  
    21. }  

    src/screens/profile.js

    1. import React, {Component} from ‘react’;  
    2. import {View,Text} from ‘react-native’;  
    3. import Icon from ‘react-native-vector-icons/Ionicons’;  
    4. export default class ProfileScreen extends Component{  
    5.     render(){  
    6.         return(  
    7.             <View>  
    8.                 <Text>this is profile screen</Text>  
    9.             </View>  
    10.         )  
    11.     }  
    12. }  
    13. ProfileScreen.navigationOptions={  
    14.     tabBarIcon:({tintColor, focused})=>(  
    15.         <Icon  
    16.             name={focused ? ‘ios-person’ : ‘md-person’}  
    17.             color={tintColor}  
    18.             size={25}  
    19.         />  
    20.     )  
    21. }  

    src/screens/settings.js

    1. import React, {Component} from ‘react’;  
    2. import {View,Text} from ‘react-native’;  
    3. import Icon from ‘react-native-vector-icons/Ionicons’;  
    4. export default class SettingScreen extends Component{  
    5.     render(){  
    6.         return(  
    7.             <View>  
    8.                 <Text>this is setting screen</Text>  
    9.             </View>  
    10.         )  
    11.     }  
    12. }  
    13. SettingScreen.navigationOptions={  
    14.     tabBarIcon:({tintColor, focused})=>(  
    15.         <Icon  
    16.             name={focused ? ‘ios-settings’ : ‘md-settings’}  
    17.             color={tintColor}  
    18.             size={25}  
    19.         />  
    20.     )  
    21. }  

    src/lib/router.js

    In router.js file, import createMaterialTopTabNavigator and createAppContainer functions of ‘react-navigation‘ library. Also import all the routers classes in it and place them in such sequence as we want to display them on the top of tab navigator.

    • activeTintColor: sets the mention color to the active router.
    • showIcon: show {true} and hide {false} the icon of routers.
    • showLabel: show {true} and hide {false} the title of routers. By default it is true.

    1. import React from ‘react’;  
    2. import {createMaterialTopTabNavigator,createAppContainer} from ‘react-navigation’;  
    3. import HomeScreen from “../screens/index”;  
    4. import ProfileScreen from “../screens/profile”;  
    5. import SettingScreen from “../screens/settings”;  
    6.   
    7. const AppNavigator = createMaterialTopTabNavigator(  
    8.     {  
    9.         Home: HomeScreen,  
    10.         Profile: ProfileScreen,  
    11.         Settings: SettingScreen,  
    12.     },  
    13.     {  
    14.         tabBarOptions: {  
    15.             activeTintColor: ‘white’,  
    16.             showIcon: true,  
    17.             showLabel:false,  
    18.             style: {  
    19.                 backgroundColor:’red’  
    20.             }  
    21.         },  
    22.     }  
    23. )  
    24. export default createAppContainer(AppNavigator);  

    src/index.js

    Import AppNavigator from ‘./lib/router’ and assign the AppNavigator in a const AppIndex in this file. Customize the status bar using StatusBar tag and add header on the top of tab navigator.

    1. import React, {Component} from ‘react’;  
    2. import {StyleSheet, Text, View,StatusBar} from ‘react-native’;  
    3. import {createAppContainer} from ‘react-navigation’;   
    4. import Icon from ‘react-native-vector-icons/Ionicons’;  
    5.   
    6. import AppNavigator from ‘./lib/router’;  
    7. const AppIndex = createAppContainer(AppNavigator)  
    8.   
    9. export default class App extends Component{  
    10.     render(){  
    11.         return(  
    12.             <View style={{flex:1}} >  
    13.                 <StatusBar  
    14.                     backgroundColor=’red’  
    15.                     barStyle=’light-content’  
    16.                 />  
    17.                 <View style={styles.header}>  
    18.                     <Icon name=’ios-camera’ size={28} color=’white’/>  
    19.                     <Icon name=’ios-menu’ size={28} color=’white’/>  
    20.                 </View>  
    21.                 <AppIndex/>  
    22.             </View>  
    23.         )  
    24.     }  
    25. }  
    26. const styles = StyleSheet.create({  
    27.     wrapper: {  
    28.         flex: 1,  
    29.     },  
    30.     header:{  
    31.         flexDirection: ‘row’,  
    32.         alignItems: ‘center’,  
    33.         justifyContent: ‘space-between’,  
    34.         backgroundColor: ‘red’,  
    35.         paddingHorizontal: 18,  
    36.         paddingTop: 5,  
    37.     }  
    38. });  

    Output:

    React Native Top Tab Navigator
  • Create Material Bottom Tab Navigator

    The material style provides an extra designing effect to tab bar at the bottom of screen. The material design makes you to switch among the different screens. The tab screen components are not mounted until the screens are first focused.

    To use the material design navigator, install react-navigation-material-bottom-tabs library as:

    1. npm install react-navigation-material-bottom-tabs react-native-paper  

    This library uses the BottomNavigation component from react-native-paper.

    It is also require to install react-native-vector-icons.

    1. createMaterialBottomTabNavigator(RouteConfigs, MaterialBottomTabNavigatorConfig);  

    Example to Create Material Bottom Tab Navigation

    In this example, we implement the material bottom tab navigator to highlights the active tab’s icons and its title. The rest of tab display only icon without the title. To use material designs, import the createMaterialBottomTabNavigator function from react-navigation-material-bottom-tabs library.

    App.js

    1. import React from ‘react’;  
    2. import {StyleSheet, Text, View,Button} from ‘react-native’;  
    3. import { createBottomTabNavigator, createAppContainer} from ‘react-navigation’;  
    4. import { createMaterialBottomTabNavigator } from ‘react-navigation-material-bottom-tabs’;  
    5. import Icon from ‘react-native-vector-icons/Ionicons’;  
    6. class HomeScreen extends React.Component {  
    7.   render() {  
    8.     return (  
    9.         <View style={styles.container}>  
    10.           <Text>Home Screen</Text>  
    11.         </View>  
    12.     );  
    13.   }  
    14. }  
    15. class ProfileScreen extends React.Component {  
    16.   render() {  
    17.     return (  
    18.         <View style={styles.container}>  
    19.           <Text>Profile Screen</Text>  
    20.         </View>  
    21.     );  
    22.   }  
    23. }  
    24. class ImageScreen extends React.Component {  
    25.     render() {  
    26.         return (  
    27.             <View style={styles.container}>  
    28.                 <Text>Image Screen</Text>  
    29.             </View>  
    30.         );  
    31.     }  
    32. }  
    33. class CartScreen extends React.Component {  
    34.     render() {  
    35.         return (  
    36.             <View style={styles.container}>  
    37.                 <Text>Cart Screen</Text>  
    38.             </View>  
    39.         );  
    40.     }  
    41. }  
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         justifyContent: ‘center’,  
    46.         alignItems: ‘center’  
    47.     },  
    48. });  
    49. const TabNavigator = createMaterialBottomTabNavigator(  
    50.     {  
    51.         Home: { screen: HomeScreen,  
    52.             navigationOptions:{  
    53.                 tabBarLabel:’Home’,  
    54.                 tabBarIcon: ({ tintColor }) => (  
    55.                     <View>  
    56.                         <Icon style={[{color: tintColor}]} size={25} name={‘ios-home’}/>  
    57.                     </View>),  
    58.             }  
    59.         },  
    60.         Profile: { screen: ProfileScreen,  
    61.             navigationOptions:{  
    62.                 tabBarLabel:’Profile’,  
    63.                 tabBarIcon: ({ tintColor }) => (  
    64.                     <View>  
    65.                         <Icon style={[{color: tintColor}]} size={25} name={‘ios-person’}/>  
    66.                     </View>),  
    67.                 activeColor: ‘#f60c0d’,  
    68.                 inactiveColor: ‘#f65a22’,  
    69.                 barStyle: { backgroundColor: ‘#f69b31’ },  
    70.             }  
    71.         },  
    72.         Image: { screen: ImageScreen,  
    73.             navigationOptions:{  
    74.                 tabBarLabel:’History’,  
    75.                 tabBarIcon: ({ tintColor }) => (  
    76.                     <View>  
    77.                         <Icon style={[{color: tintColor}]} size={25} name={‘ios-images’}/>  
    78.                     </View>),  
    79.                 activeColor: ‘#615af6’,  
    80.                 inactiveColor: ‘#46f6d7’,  
    81.                 barStyle: { backgroundColor: ‘#67baf6’ },  
    82.             }  
    83.         },  
    84.         Cart: {  
    85.             screen: CartScreen,  
    86.             navigationOptions:{  
    87.                 tabBarLabel:’Cart’,  
    88.                 tabBarIcon: ({ tintColor }) => (  
    89.                     <View>  
    90.                         <Icon style={[{color: tintColor}]} size={25} name={‘ios-cart’}/>  
    91.                     </View>),  
    92.             }  
    93.         },  
    94.     },  
    95.     {  
    96.       initialRouteName: “Home”,  
    97.       activeColor: ‘#f0edf6’,  
    98.       inactiveColor: ‘#226557’,  
    99.       barStyle: { backgroundColor: ‘#3BAD87’ },  
    100.     },  
    101. );  
    102.   
    103. export default createAppContainer(TabNavigator);  

    Output:

    React Native Create Material Button Tab Navigator
    React Native Create Material Button Tab Navigator
    React Native Create Material Button Tab Navigator
  • Adding Icons at the Bottom of Tab Navigation

    In this section, we will add the icons to the bottom of Tab Navigation. Before dive in this tutorial, go through the previous tutorial Tab Navigation, where we describe how to implement Bottom Tab Navigation.

    Example to Add Icons at the Bottom of Tab Navigation

    First add the required library and dependency to the React Native project:

    1. Add the react navigation library by using the following command:

    1. yarn add react-navigation  

    2. Add the react native gesture handler library by using the following command:

    1. yarn add react-native-gesture-handler  

    3. Add the react native vector icons library by using the following command:

    1. yarn add react-native-vector-icons  

    After the successful execution of above command, link these libraries to react native project using the bellow command:

    1. react-native link  

    The above command adds the below dependencies in D:\your_directory\your_reactNativeProject\package.json file.

    1. “react-native-gesture-handler”: “^1.1.0”,  
    2. “react-native-vector-icons”: “^6.3.0”,  
    3. “react-navigation”: “^3.3.2”  

    D:\your_directory\your_reactNativeProject\android\app\build.gragle

    1. implementation project(‘:react-native-vector-icons’)  
    2. implementation project(‘:react-native-gesture-handler’)  

    D:\your_directory\your_reactNativeProject\android\settings.gradle file:

    1. include ‘:react-native-vector-icons’  
    2. project(‘:react-native-vector-icons’).projectDir = new File(rootProject.projectDir, ‘..\node_modules\react-native-vector-icons\android’)  
    3. include ‘:react-native-gesture-handler’  
    4. project(‘:react-native-gesture-handler’).projectDir = new File(rootProject.projectDir, ‘..\node_modules\react-native-gesture-handler\android’)  

    Make slightly change (replace ‘\’ with ‘/’) in above route structures as:

    1. include ‘:react-native-vector-icons’  
    2. project(‘:react-native-vector-icons’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-vector-icons/android’)  
    3. include ‘:react-native-gesture-handler’  
    4. project(‘:react-native-gesture-handler’).projectDir = new File(rootProject.projectDir, ‘../node_modules/react-native-gesture-handler/android’)  

    D:\your_directory\your_reactNativeProject\android\app\src\main\java\com\ reactNativeProject\MainApplication.java

    1. import com.oblador.vectoricons.VectorIconsPackage;  
    2. import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;  
    3. . . .  
    4. protected List<ReactPackage> getPackages() {  
    5.   return Arrays.<ReactPackage>asList(  
    6.       new MainReactPackage(),  
    7.         new VectorIconsPackage(),  
    8.         new RNGestureHandlerPackage()  
    9.   );  
    10. }  

    App.js

    Create two classes “HomeScreen” and “ProfileScreen” for two tab “Home” and “Profile” respectively. The createBottomTabNavigator function creates a tab bar on the bottom of the screen which provides you to switch between different routes.

    Map the “HomeScreen” to “Home” and “ProfileScreen” to “Profile” title. The Icon tag adds the icon to tabs navigation. We can use the different icon name from ionicons.com

    1. import React from ‘react’;  
    2. import {StyleSheet, Text, View} from ‘react-native’;  
    3. import { createBottomTabNavigator, createAppContainer } from ‘react-navigation’;  
    4. import Icon from ‘react-native-vector-icons/Ionicons’;  
    5. class HomeScreen extends React.Component {  
    6.   render() {  
    7.     return (  
    8.         <View style={styles.container}>  
    9.           <Text>Home Screen</Text>  
    10.         </View>  
    11.     );  
    12.   }  
    13. }  
    14. class ProfileScreen extends React.Component {  
    15.   render() {  
    16.     return (  
    17.         <View style={styles.container}>  
    18.           <Text>Profile Screen</Text>  
    19.         </View>  
    20.     );  
    21.   }  
    22. }  
    23.   
    24. const TabNavigator = createBottomTabNavigator(  
    25.     {  
    26.       Home:{  
    27.         screen:HomeScreen,  
    28.         navigationOptions:{  
    29.           tabBarLabel:’Home’,  
    30.           tabBarIcon:({tintColor})=>(  
    31.               <Icon name=”ios-home” color={tintColor} size={25}/>  
    32.           )  
    33.         }  
    34.       },  
    35.       Profile: {  
    36.         screen:ProfileScreen,  
    37.         navigationOptions:{  
    38.           tabBarLabel:’Profile’,  
    39.           tabBarIcon:({tintColor})=>(  
    40.               <Icon name=”ios-person” color={tintColor} size={25}/>  
    41.           )  
    42.         }  
    43.       },  
    44.     },  
    45.     {  
    46.       initialRouteName: “Home”  
    47.     },  
    48. );  
    49. const styles = StyleSheet.create({  
    50.   container: {  
    51.     flex: 1,  
    52.     justifyContent: ‘center’,  
    53.     alignItems: ‘center’  
    54.   },  
    55. });  
    56.   
    57. export default createAppContainer(TabNavigator);  

    Output:

    React Native Adding Icons at the Bottom of Tab Navigation
    React Native Adding Icons at the Bottom of Tab Navigation
  • React Native Tab Navigation

    React Native Tab Navigation is the most common navigation style in the mobile applications. The Tab Navigation is tabbed at the bottom of the screen or on the top below the header or sometimes as a header. It is used to switch between different route screens.

    To create Tab-based navigation, import createBottomTabNavigator and createAppContainer in the root functions of the react-navigation library.

    Bottom Tab Navigator Configuration

    There are various configurable props of BottomTabNavigator. Some of them are:

    PropDescription
    initialRouteNameIt defines the initial tab route when the app first loads.
    orderIt is an array of route screen, which sets the order of the tabs.
    pathsIt provides the mapping of route screen to path config, which overrides the paths set in the routeConfigs.
    lazySetting it as {true} makes the tab to rendered when the tab becomes active for the first time. If it is set to false, all tabs are rendered immediately. Its default value is true.
    tabBarComponentIt overrides the component, which is used as the tab bar. It is optional.
    tabBarOptionsIt is an object of the following properties: activeTintColor, activeBackgroundColor, inactiveTintColor , inactiveBackgroundColor, showLabel, showIcon, style, labelStyle, tabStyle, allowFontScaling.

    Tab – based navigation Example

    Create the two classes named as HomeScreen and ProfileScreen. Register these classes in createBottomTabNavigator function with Home and Profile tab respectively.

    1. import React from ‘react’;  
    2. import { StyleSheet, Text, View } from ‘react-native’;  
    3. import { createBottomTabNavigator, createAppContainer } from ‘react-navigation’;  
    4.   
    5. class HomeScreen extends React.Component {  
    6.     render() {  
    7.         return (  
    8.             <View style={styles.container}>  
    9.                 <Text>Home Screen</Text>  
    10.             </View>  
    11.         );  
    12.     }  
    13. }  
    14. class ProfileScreen extends React.Component {  
    15.     render() {  
    16.         return (  
    17.             <View style={styles.container}>  
    18.                 <Text>Profile Screen</Text>  
    19.             </View>  
    20.         );  
    21.     }  
    22. }  
    23.   
    24. const TabNavigator = createBottomTabNavigator({  
    25.     Home: HomeScreen,  
    26.     Profile: ProfileScreen,  
    27. });  
    28. const styles = StyleSheet.create({  
    29.     container: {  
    30.         flex: 1,  
    31.         justifyContent: ‘center’,  
    32.         alignItems: ‘center’  
    33.     },  
    34. });  
    35.   
    36. export default createAppContainer(TabNavigator);  

    Output:

    React Native Tab Navigation
    React Native Tab Navigation

    If we set the initialRouteName: “Profile” then, it loads the “ProfileScreen” as an initial route tab.

    1. const TabNavigator = createBottomTabNavigator({  
    2.         Home: HomeScreen,  
    3.         Profile: ProfileScreen,  
    4.     },  
    5.     {  
    6.         initialRouteName: “Profile”  
    7.     }  
    8. );