React Native Modal Tutorial with Examples

Last Updated on by in React Native
A comprehensive step by step tutorial on how to work with React Native Modal component. In this tutorial, we will learn how to show essential content such as text and image with Modal popup in React Native application.React Native Modal Tutorial with Examples

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

If you need more control over how to present modals over the rest of your app, then consider using a top-level Navigator.

Working with modal popups has been made easy by built-in React Native Modal component. In this tutorial, we will check out the various react-native modal examples, and show you how you can add different controls over the modal component to customize it to the next level.

React Native Modal Example

Prerequisite

Following tools, frameworks, and packages required to get started with this tutorial.

  • Node.js
  • NPM
  • React-Native
  • React-Native CLI
  • Text Editor or IDE
  • Xcode or Android Studio

Initiate React Native Project

Run command in the terminal to globally Install the latest React Native CLI version.

npm install -g react-native-cli

Let’s start installing the React Native app first.

react-native init modalreactnative

Head over to the project directory.

cd modalreactnative

Run the 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 center of the Apple development experience. Robustly blended with the Cocoa and Cocoa Touch frameworks, Xcode is an astonishingly productive environment for developing apps for Mac, iPhone, iPad, Apple Watch, and Apple TV.

Here is the process to download Xcode from Apple site.

  • Visit Apple Developer
  • Click on develop
  • Click on downloads and sign in
  • Scroll to the bottom and click see more downloads
  • Use the search bar to search up Xcode
  • Click the little plus icon on the row with the Xcode version you want
  • Click download on the zip file

Or even you can visit the following URL to download Xcode.

Next, set the Xcode path for command line tool. Go to Xcode > Preferences > Locations Here set the Command Line Tools: Xcode xx.x.x (version number) from the dropdown.

Run React Native App in Xcode Emulator

Next, run the following command to install cocoapods.

sudo gem install cocoapods

Next, get inside the ios folder of your project.

cd ios

Now, run the command while staying in the ios folder.

pod install

Then, we are all set with configuration, come out from the iOS folder and run the command in the terminal to start the app in the iOS emulator using Xcode.

react-native run-ios

demo modal react native

To run your app in an Android device or emulator, you have to set the android development environment in your machine and run the following command.

react-native run-android

Add Button to Open Modal Dialog

We are about to add a cool stylish button in our react-native application, and this button will be responsible for opening the Modal when the user clicks on this button.

However, we are not going to use the Button component. Instead, we will use the TouchableOpacity component to create and add a custom styling in a button.

Open the App.js file and replace 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 step we will learn how to implement Simple Modal in React Native with some content (Image and Text). Open the App.js file 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,
  }
});

We imported the Modal component along with Image and Text components.

We defined the initial state of the Modal, the displayModal() is a function that set the Modal state to true if its false.

In the following react native modal example, we implemented the animated Modal by just setting the animation property to ‘slide’. Apart from that, you can also choose ‘fade’ or ‘none’ prop to animate the modal.

To set the React Native Modal’s transparent background, we set the transparent property to false.

We are showing 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, add the following code inside the Modal component.

<Text style={styles.closeText}
  onPress={() => {
   this.displayModal(!this.state.isVisible);}
  }> Close Modal </Text>

Here is the style for close button.

const styles = StyleSheet.create({
  closeText: {
    fontSize: 24,
    color: '#00479e',
    textAlign: 'center',
  }
});

And, here is 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',
  }
});

Modal Methods & Properties

There are various other properties which can allow us to customize Modal to some extent. We will have a look at the useful methods and properties to work with Modal. However, you can visit the following URL to check out the full details about Modal props.

Visible – This property makes sure whether your modal should be visible or not. It takes two parameters, either true or false.

supportedOrientations: The supportedOrientations prop lets the modal to be wheeled to any of the specified orientations.

On iOS, the modal is still restricted by what’s specified in your app’s Info.plist’s UISupportedInterfaceOrientations field. When using presentationStyle of pageSheet or formSheet, this property will be ignored by iOS.

animationType: The animationType prop manages how modal should be animated. However, the default prop is set to be none.

  • fade into view
  • slides in from the bottom
  • shows without animation

hardwareAccelerated: This property examines whether to enforce hardware acceleration for the underlying window.

presentationStyle: This value examines how the modal should appear (usually on larger devices like iPad or larger iPhones).

  • fullScreen comprises the screen perfectly
  • formSheet overlays narrow-width composition centered
  • pageSheet covers portrait-width view centered (exclusively on larger devices)
  • overFullScreen includes the screen effectively but concedes clarity

React Native Basic Modal

Have you thought of a modal that we can observe in a lot of simplistic applications? In such cases, the perceptibility of the modal is handled privately by some component’s local state.

Possibly something 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

Thats it for now, finally we have completed React Native Modal tutorial in this tutorial we have learned how to display modal in iOS and Android app with some data. We have learned how to show and hide modal popup in React native app and also focused on basic styling of components using style.classname property in React Native.

You can get the full code of this tutorial on this GitHub repo.

Happy Coding!