More

    Everything About React Native Model

    React Native Modal: An Introduction

    A Modal is a pre-defined component that aids us in the process of creating the modal popup to React Native. Ordinarily, a Modal component is a primary way to present content above an enclosing view. 

     For instance, what if you want more control over how to present modals over the rest of your app. In that case you must then consider using a top-level navigator. 

     Most importantly you first need to know the main goal of React Native Model. Above all, certainly the goal is to expand the original react-native Modal component. To do so, we further need to add animations and styles customization options. In addition to it, we will still need to provide a plain-simple API. 

     

    A few features of the React Native Modal are- 

     

    –       It allows us to smoothly enter/exit animations.

    –       It lets us use plain, simple and flexible APIs

    –       Allows us to customize the backdrop opacity, color and timing. 

    –       It includes listeners for the modal animation endings

    –       Resizes itself correctly on device rotation

    –       Makes the application swipeable 

    –       Allows us to make the app scrollable. 

    Setup- 

     This library is available on npm. You can install it with npm – react-native-modal or yarn add react-native-modal. 

    Prerequisite-

    Most importantly, before starting you will need to check a few things. Those are whether you have the following tools, frameworks and packages or not. To continue further you will need:

     

    –       Node.js

    –       NPM

    –       React-Native

    –       React-Native CLI

    –       Text Editor or IDE

    –       Xcode or Android Studio. 

     

     Initiate the React Native Project- 

     Run the command given below in the terminal to globally install the latest React Native CLI version: 

     npm install -g react-native-cli

     

    Let us install the react native app first: 

    react-native init modalreactnative

     

    The next step would be to head over to the project directory. 

    cd modalreactnative

     

    Run the below command to check the installed React Native version: 

    react-native -v

     

    # react-native-cli: 2.0.1

    # react-native: 0.61.5

     

    Run React Native App with Xcode Emulator-

    The Xcode IDE is at the centre of the Apple development experience. It is very well blended with the Cocoa and Cocoa Touch frameworks and is an astonishingly productive environment for the development of apps for Mac, iPhone, iPad, Apple Watch and Apple TV.

     

    Given below is the process that allows you to download the Xcode from the Apple site: 

    –       First, visit Apple Developer

    –       Click on the develop option

    –       Click on downloads and sign into your account. 

    –       Next, scroll to the bottom and click on see more downloads

    –       Search up Xcode, on the search bar. 

    –       Click the tiny plus icon on the row with the Xcode version you want. 

    –       Click and download the zip file. 

     

    The next step will be to set up a path for the Xcode using the command line tool. 

    The process to do this is: 

    –       Go to Xcode

    –       Preferences

    –       Locations and find the command line tools: Xcode xx.x.x (version number) from the dropdown. 

    Next run the following command to install cocoapods: 

    sudo gem install cocoapods

    Later on we need to get inside the ios folder of your project by using the following code: 

    cd ios 

    Furthermore, run the following command while staying in the iOS folder: 

    pod install

     

    After completing the above mentioned steps, we are all set with the configuration. All we need to do now is come out of the iOS folder and run the command in the terminal to start the app in the iOS emulator using Xcode.

     

    react-native run-ios

     

    To run your app on an Android device or emulator you would need to follow some steps. Firstly you need to set up the android development environment on your machine. Further you simply just need to run the following command: 

    react-native run-android

     

     Add Button to Open Modal Dialog: 

     

    Further we will learn how to add a cool and also stylish button to our react-native application. Moreover, this button will also be responsible for opening the Modal. But this action will only occur when the user clicks on this button.

    However, most importantly you need to remember that we are not going to use the Button  component. On the other hand, we are going to use touchableOpacity component. As a result it will create and give a custom styling to a button. 

    Firstly, let us open the App.js file. After that we need to replace it with the following code: 

    // App.js

     

    import React, { Component } from ‘react’;

    import { 

      View,

      Text,

      StyleSheet,

      TouchableOpacity

    } from ‘react-native’;

     

    export default class App extends Component {

     

      render() {

        return (

          <View style = { styles.container }>

             <TouchableOpacity

                  style={styles.button}

                  onPress={() => {

                    this.displayModal(true);

                  }}>

                  <Text style={styles.buttonText}>Show Modal</Text>

              </TouchableOpacity>          

            </View>

          );

      }

    };

     

    const styles = StyleSheet.create({

      container: {

        padding: 25,

        flex: 1,

        alignItems: ‘center’,

        justifyContent: ‘center’,

      },

      button: {

        display: ‘flex’,

        height: 60,

        borderRadius: 6,

        justifyContent: ‘center’,

        alignItems: ‘center’,

        width: ‘100%’,

        backgroundColor: ‘#2AC062’,

        shadowColor: ‘#2AC062’,

        shadowOpacity: 0.5,

        shadowOffset: { 

          height: 10, 

          width: 0 

        },

        shadowRadius: 25,

      },  

    });

     

     

    Show React Native Modal- 

    In this next step, we will learn how to implement Simple Modal in React Native with some image and text content. 

    To do so, open the App.js file once again and place the following code in it. 

     

    // App.js

     

    import React, { Component } from ‘react’;

    import { 

      View,

      Text,

      StyleSheet,

      TouchableOpacity,

      Image,

      Modal

    } from ‘react-native’;

     

    export default class App extends Component {

      // initial state

      state = {

        isVisible: false

      };

     

      // hide show modal

      displayModal(show){

        this.setState({isVisible: show})

      }

     

      render() {

        return (

          <View style = { styles.container }>

            <Modal

                animationType = {“slide”}

                transparent={false}

                visible={this.state.isVisible}

                onRequestClose={() => {

                  Alert.alert(‘Modal has now been closed.’);

                }}>

     

                <Image 

                  source={require(‘./assets/scooby.jpeg’)}

                  style = { styles.image }/>

                  <Text style = { styles.text }>

                      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

                      Maecenas eget tempus augue, a convallis velit.</Text>

              </Modal>

                

              <TouchableOpacity

                  style={styles.button}

                  onPress={() => {

                    this.displayModal(true);

                  }}>

                  <Text style={styles.buttonText}>Show Modal</Text>

              </TouchableOpacity>          

            </View>

          );

      }

    };

     

    const styles = StyleSheet.create({

      container: {

        padding: 25,

        flex: 1,

        alignItems: ‘center’,

        justifyContent: ‘center’,

      },

      button: {

        display: ‘flex’,

        height: 60,

        borderRadius: 6,

        justifyContent: ‘center’,

        alignItems: ‘center’,

        width: ‘100%’,

        backgroundColor: ‘#2AC062’,

        shadowColor: ‘#2AC062’,

        shadowOpacity: 0.5,

        shadowOffset: { 

          height: 10, 

          width: 0 

        },

        shadowRadius: 25,

      },

      closeButton: {

        display: ‘flex’,

        height: 60,

        borderRadius: 6,

        justifyContent: ‘center’,

        alignItems: ‘center’,

        backgroundColor: ‘#FF3974’,

        shadowColor: ‘#2AC062’,

        shadowOpacity: 0.5,

        shadowOffset: { 

          height: 10, 

          width: 0 

        },

        shadowRadius: 25,

      },

      buttonText: {

        color: ‘#FFFFFF’,

        fontSize: 22,

      },

      image: {

        marginTop: 150,

        marginBottom: 10,

        width: ‘100%’,

        height: 350,

      },

      text: {

        fontSize: 24,

        marginBottom: 30,

        padding: 40,

      }

    });

     

    By doing this, we imported the Modal component along with the text and image components. We defined the initial state of Modal, the displayModal() is a function that sets the Modal state to true if it is false. 

    As you can see above we need to set the animation property to ‘slide’.  Further we need to implement the animated Modal. We also have other options to use such as ‘fade’ and ‘ none’.

    In order to have a transparent background, set the transparent property as false.

    We show the image and text in the Modal and added the style for the components using {styles.className} property. 

     

     

    Close React Native Modal Popup. 

    Next, we will understand how to close the React Native Modal. To do so, we will need to add below code into the previous one:

     

    <Text style={styles.closeText}

      onPress={() => {

       this.displayModal(!this.state.isVisible);}

      }> Close Modal </Text>

     

    Next we will add the style for the close button: 

    const styles = StyleSheet.create({

      closeText: {

        fontSize: 24,

        color: ‘#00479e’,

        textAlign: ‘center’,

      }

    });

     

     

    Lastly, we will add the final App.js code: 

    // App.js

     

    import React, { Component } from ‘react’;

    import { 

      View,

      Text,

      StyleSheet,

      TouchableOpacity,

      Image,

      Modal

    } from ‘react-native’;

     

    export default class App extends Component {

      // initial state

      state = {

        isVisible: false

      };

     

      // hide show modal

      displayModal(show){

        this.setState({isVisible: show})

      }

     

      render() {

        return (

          <View style = { styles.container }>

            <Modal

                animationType = {“slide”}

                transparent={false}

                visible={this.state.isVisible}

                onRequestClose={() => {

                  Alert.alert(‘Modal has now been closed.’);

                }}>

     

                <Image 

                  source={require(‘./assets/scooby.jpeg’)}

                  style = { styles.image }/>

                  <Text style = { styles.text }>

                      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

                      Maecenas eget tempus augue, a convallis velit.</Text>

     

                  <Text 

                    style={styles.closeText}

                    onPress={() => {

                      this.displayModal(!this.state.isVisible);}}>Close Modal</Text>

              </Modal>

                

              <TouchableOpacity

                  style={styles.button}

                  onPress={() => {

                    this.displayModal(true);

                  }}>

                  <Text style={styles.buttonText}>Show Modal</Text>

              </TouchableOpacity>          

            </View>

          );

      }

    };

     

    const styles = StyleSheet.create({

      container: {

        padding: 25,

        flex: 1,

        alignItems: ‘center’,

        justifyContent: ‘center’,

      },

      button: {

        display: ‘flex’,

        height: 60,

        borderRadius: 6,

        justifyContent: ‘center’,

        alignItems: ‘center’,

        width: ‘100%’,

        backgroundColor: ‘#2AC062’,

        shadowColor: ‘#2AC062’,

        shadowOpacity: 0.5,

        shadowOffset: { 

          height: 10, 

          width: 0 

        },

        shadowRadius: 25,

      },

      closeButton: {

        display: ‘flex’,

        height: 60,

        borderRadius: 6,

        justifyContent: ‘center’,

        alignItems: ‘center’,

        backgroundColor: ‘#FF3974’,

        shadowColor: ‘#2AC062’,

        shadowOpacity: 0.5,

        shadowOffset: { 

          height: 10, 

          width: 0 

        },

        shadowRadius: 25,

      },

      buttonText: {

        color: ‘#FFFFFF’,

        fontSize: 22,

      },

      image: {

        marginTop: 150,

        marginBottom: 10,

        width: ‘100%’,

        height: 350,

      },

      text: {

        fontSize: 24,

        marginBottom: 30,

        padding: 40,

      },

      closeText: {

        fontSize: 24,

        color: ‘#00479e’,

        textAlign: ‘center’,

      }

    });

     

    React Native Basic Modal- 

    In cases of modals where you can observe simplistic applications, the perceptibility of the modal is handled privately by some component’s local state. 
     

    The code can be similar to this: 

    class ModalDialog extends Component {

      state = { 

        isConfirmed: false 

      };

     

      submitEvent = value => {

        this.setState({ isConfirmed: true, value: value });

      };

     

      // Handler when user tries to confirm choices in modal popup

      confirmEvent = () => {

        // …

      };

     

      // Handler when user tries to cancel confirmation modal popup

      cancelEvent = () => {

        this.setState({ isConfirmed: false });

      };

     

      render() {

        const { isConfirmed } = this.state;

     

        return (

          <View style={styles.container}>

              {isConfirmed && <Dialog onCancel={this.cancelEvent} onConfirm={this.confirmEvent} />}

          </View>

        );

      }

    }

     

    export default ModalDialog;

     

    Conclusion:

    To sum up, at present we also know how to display modal in iOS and Android Apps by using some data. Moreover, we have also learned to show and hide modal popup in React native apps. Further we have additionally focused on basic styling of components. Due to which we have used style.classname property to get the output in React Native.

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here