Category: 7. Misc

https://cdn-icons-png.flaticon.com/512/9786/9786511.png

  • React Native Splash Screen

    Splash Screen is a view which contains Text or Images that shows when the app first starts. It is used when the mobile app requires essential information before its start. The application may load the information from some external API or local storage.

    Without that information, the application may not be able to display the user interface. For example, the application requires checking whether the user is authorized and deciding which screen is to display.

    The Splash Screen will automatically hide after a few seconds (3-5) from the screen and display when the application starts next time.

    Splash Screen Example

    1. Import Platform, StyleSheet, View, Text, Image, TouchableOpacity, and Alert components in your project.
    2. Create constructor() in the project and make a Boolean type state named as isVisible and set its default value true. This state is used to show and hide the Splash screen.
    3. Create a function named as Hide_Splash_Screen(). It changes the state value as false.
    4. Create componentDidMount() method in your class. It is an inbuilt method and called when the app fully loaded. In the same method, we can use the setTimeout() JavaScript function to change the state after a given time.

    App.js

    1. import React, { Component } from ‘react’;  
    2.  import { Platform, StyleSheet, View, Text,  
    3.  Image, TouchableOpacity, Alert } from ‘react-native’;  
    4.  export default class Myapp extends Component<{}>  
    5. {  
    6.    constructor(){  
    7.      super();  
    8.      this.state={  
    9.      isVisible : true,  
    10.     }  
    11.   }  
    12.    Hide_Splash_Screen=()=>{  
    13.     this.setState({   
    14.       isVisible : false   
    15.     });  
    16.   }  
    17.    
    18.   componentDidMount(){  
    19.     var that = this;  
    20.     setTimeout(function(){  
    21.       that.Hide_Splash_Screen();  
    22.     }, 5000);  
    23.    }  
    24.    
    25.     render()  
    26.     {  
    27.         let Splash_Screen = (  
    28.              <View style={styles.SplashScreen_RootView}>  
    29.                  <View style={styles.SplashScreen_ChildView}>  
    30.                        <Image source={{uri:’https://images.tpointtech.com/tutorial/react-native/images/react-native-tutorial.png’}}  
    31.                     style={{width:’100%’, height: ‘100%’, resizeMode: ‘contain’}} />  
    32.                 </View>  
    33.              </View> )  
    34.          return(  
    35.              <View style = { styles.MainContainer }>  
    36.                 <Text style={{textAlign: ‘center’}}> Splash Screen Example</Text>  
    37.                  {  
    38.                   (this.state.isVisible === true) ? Splash_Screen : null  
    39.                 }  
    40.             </View>  
    41.               );  
    42.     }  
    43. }  
    44.  const styles = StyleSheet.create(  
    45. {  
    46.     MainContainer:  
    47.     {  
    48.         flex: 1,  
    49.         justifyContent: ‘center’,  
    50.         alignItems: ‘center’,  
    51.         paddingTop: ( Platform.OS === ‘ios’ ) ? 20 : 0  
    52.     },  
    53.    
    54.     SplashScreen_RootView:  
    55.     {  
    56.         justifyContent: ‘center’,  
    57.         flex:1,  
    58.         margin: 10,  
    59.         position: ‘absolute’,  
    60.         width: ‘100%’,  
    61.         height: ‘100%’,  
    62.       },  
    63.    
    64.     SplashScreen_ChildView:  
    65.     {  
    66.         justifyContent: ‘center’,  
    67.         alignItems: ‘center’,  
    68.         backgroundColor: ‘#00BCD4’,  
    69.         flex:1,  
    70.     },  
    71. });  

    Output:

    React Native Splash Screen
  • 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