AppDividend
Latest Code Tutorials

React Native Modal Example | Modal In React Native

8

React Native Modal Example is today’s leading topic. In this demo, we will see how we can display the Modal and show the data inside that Modal. For this tutorial, we use React Native component called Modal to display the image and text. It is a straightforward demo, but very useful React Native Modal Tutorial. So let us dive into it.

React Native Modal Example

I’ve been working recently with modal popups in React Native (again!) and realized it’s a recurring pattern in a lot of applications that’s worth writing a bit about. So, here are a few of my lessons learned over implementing modal dialogs over and over again.

Note: For a lot of cases you might be just fine using the built-in Modal component from React Native. If that solves your problem, all the power to you!

Okay, first let us install React Native Project.

#1: Install React Native on Mac.

If you have not installed React Native CLI globally then install it using the following command.

npm install -g react-native-cli

Okay, now for creating a new application, type the following command.

react-native init rncreate
cd rncreate

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios

Open the Project in your favorite editor.

code .

#2: Add a Button.

We will display the two things inside the Modal.

  1. Text
  2. Image

So inside the root, create one folder called assets and inside that create one folder called images and add an image from your local machine and copy the image in this folder.

Okay, now Add the Button and Image inside Container View. Type the following code inside App.js.

// App.js

import React, { Component } from 'react';
import Krunal from './assets/images/Krunal.jpg';
import { View, Button, StyleSheet } from 'react-native';

export default class App extends Component {

  render() {
    	return (
        <View style = { styles.container }>
          <Button 
            onPress = { () => console.log('Button Pressed') }
            title = "Open Modal"
            color = "orange">
          </Button>
        </View>
      )
    }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 300,
  }
});

So, here we have added one Button, and also, we have imported the image file. Right now, we have not used it yet, but we will use it in a minute. 

Our goal is when the user clicks the button, Modal will pop up otherwise it will not pop up, and we can’t see it. So, now we import one more component and pass the Image and Text as a prop to that component.

Also, by default Modal is always open, so we need to handle it our way. That is why we need the state which we can control, and ultimately we control the Modal.

#3: Create DisplayModal.js file.

Now, create one folder inside root called components and inside that create one file called DisplayModal.js and add the following code.

// DisplayModal.js

import React from 'react'
import { Modal, View, Image, Text, StyleSheet } from 'react-native';

const DisplayModal = (props) => (
  <Modal visible={ props.display } animationType = "slide" 
         onRequestClose={ () => console.log('closed') }>>
    <View>
      <Image 
        source = { props.image } 
        style = { styles.image } />
      <Text style = { styles.text }>
        { props.data }
      </Text>
    </View>
  </Modal>
)

const styles = StyleSheet.create({
  image: {
    marginTop: 20,
    marginLeft: 90,
    height: 200,
    width: 200
  },
  text: {
    fontSize: 20,
    marginLeft: 150
  }
})

export default DisplayModal;

DisplayModal is a static component, and it has nothing to do with the State. So I have used it as a functional component. It just accepts the props and displays them in the styled form.

You can note that we have used Modal’s visible property. So when it is true, we can see the Modal otherwise we don’t see the Modal. Thus it is controlled by the parent component, and in our case it is App.js.

So when the user clicks, we change the state of the display property inside App.js to true, and now we can see the Modal.

Now, write the following code inside an App.js file.

// App.js

import React, { Component } from 'react';
import Krunal from './assets/images/Krunal.jpg';
import { View, Button, StyleSheet } from 'react-native';
import DisplayModal from './components/DisplayModal';

export default class App extends Component {

  state = {
    display: false
  }

  triggerModal() {
    this.setState(prevState => {
      return {
        display: true
      }
    });
  }

	render() {
    	return (
        <View style = { styles.container }>
          <Button 
            onPress = { () => this.triggerModal() }
            title = "Open Modal"
            color = "orange">
          </Button>
          <DisplayModal 
            image = { Krunal }
            data = "Krunal"
            display = { this.state.display }
          />
        </View>
      )
  	}
}

const styles = StyleSheet.create({
  container: {
    marginTop: 300,
  }
});

So, here, we have defined the one state called display, and by default it is false. When the user clicks on the button, it will change to true, and we can see the Modal will popup.

React Native Modal Example | Tutorial

#4: Modal Properties.

You can find out more about Modal Properties on this Link.

Here, we have used one Modal property called animationType.

animationType

It has the following values.

  1. slide:  slides in from the bottom.
  2. fade:  fades into view.
  3. none:  appears without an animation.

We have used the slide, but you can try to fade and see how it can change the layout animation effect.

Visible

The visible property accepts two arguments.

  1. true
  2. false

If it is true, then it will be visible inside the screen otherwise not. We have passed the property of visible inside Modal when the button is clicked.

Finally, React Native Modal Example | Modal In React Native Tutorial is over.

The basic version of React Native Modal Popup

Let’s imagine a modal that we can see in a lot of simple applications. In such a basic case, the visibility of the modal is managed internally by some component’s local state. See the following code.

class NewScreen extends Component {
  state = { showConfirmation: false };

  handleSubmit = value => {
    this.setState({ showConfirmation: true, value: value });
  };

  // Handler for when the user confirms their choice in the modal
  handleConfirm = () => {
    // …
  };

  // Handler for when the user cancels the confirmation dialog
  handleCancel = () => {
    this.setState({ showConfirmation: false });
  };

  render() {
    const { showConfirmation } = this.state;

    return (
      <View style={styles.container}>
        {showConfirmation && <Dialog onCancel={this.handleCancel} onConfirm={this.handleConfirm} />}
      </View>
    );
  }
}

export default NewScreen;

This is a typical modal that I’ve seen many times. Its visibility is handled by the parent component by changing its inner state.

We would get showConfirmation from the local state and depending on whether it’s set or not, show or hide the confirmation dialog.

We would also pass there the handleConfirm and handleCancelbuttons that would take care of the logic that should happen when the user presses any of those.

The main advantages of this solution are that it’s simple, easy to read (and reason about) and easy to customize in every view.

The main disadvantages are that even though it’s simple, there’s management code that we need to write in every component that uses it and it can be customized wherever it’s used which makes it difficult to change it globally.

Recommended Posts

React Native Swipe Components

React Native Drawer Navigator Example

React Native Tab View Example

Native Navigation using React Native Navigation

React Native Redux Example Tutorial

React Native Fetch Example

React Native Animation Tutorial

React Native FlatList Example

React Native Firebase Example

How To Setup React Native Using Expo

8 Comments
  1. Usman says

    krunal !
    how to add onPress event on this modal.when i am click on button which is locate on modal screen.
    and my function late on my root file can function will run??
    thankyou

  2. Banga Lee says

    If you have a list view, how do you dynamically pass data from list view to the modal

  3. Arup Maitra says

    @BangaLee — If you want to pass listview data inside of modal then you have to pass those datas as a prop like in this example image and visibility value has been passed. I hope it will help you.

  4. Arup Maitra says

    @Usman — If you want to invoke some function which is inside of root folder then you have to manage this functionality very carefully like you have to be introduce a separate js file (like util.js) where this generic method will be exposed. Then you can use that function by importing this file from Modal.js file. I hope it will help you.

  5. Kay says

    thanks for your post! any chance you could add in an explanation of how to close the modal?

    1. Fana says

      you set the “display” state to its initial state which is = false

  6. Dmitriy says

    DisplayModal.js – a typo «>>»in the line:
    onRequestClose={ () => console.log(‘closed’) }>>

  7. skptricks says

    If you have a list view, how do you dynamically pass data from list view to the modal

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.