React Native - Modal


Advertisements

In this chapter, we will show you how to use the modal component in React Native.

Let us now create a new file: ModalExample.js

We will put logic inside ModalExample. We can update the initial state by running the toggleModal.

After updating the initial state by running the toggleModal, we will set the visible property to our modal. This prop will be updated when the state changes.

The onRequestClose is required for Android devices.

App.js

import React, { Component } from 'react'
import WebViewExample from './modal_example.js'

const Home = () => {
   return (
      <WebViewExample/>
   )
}
export default Home;

modal_example.js

import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet}

from 'react-native'
class ModalExample extends Component {
   state = {
      modalVisible: false,
   }
   toggleModal(visible) {
      this.setState({ modalVisible: visible });
   }
   render() {
      return (
         <View style = {styles.container}>
            <Modal animationType = {"slide"} transparent = {false}
               visible = {this.state.modalVisible}
               onRequestClose = {() => { console.log("Modal has been closed.") } }>
               
               <View style = {styles.modal}>
                  <Text style = {styles.text}>Modal is open!</Text>
                  
                  <TouchableHighlight onPress = {() => {
                     this.toggleModal(!this.state.modalVisible)}}>
                     
                     <Text style = {styles.text}>Close Modal</Text>
                  </TouchableHighlight>
               </View>
            </Modal>
            
            <TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
               <Text style = {styles.text}>Open Modal</Text>
            </TouchableHighlight>
         </View>
      )
   }
}
export default ModalExample

const styles = StyleSheet.create ({
   container: {
      alignItems: 'center',
      backgroundColor: '#ede3f2',
      padding: 100
   },
   modal: {
      flex: 1,
      alignItems: 'center',
      backgroundColor: '#f7021a',
      padding: 100
   },
   text: {
      color: '#3f2949',
      marginTop: 10
   }
})

Our starting screen will look like this −

React Native Open Modal

If we click the button, the modal will open.

React Native Modal

Useful Video Courses


Video

ReactJS Online Training

20 Lectures 1.5 hours

Anadi Sharma

Video

Create Virtual Reality Apps using React VR & React 360

61 Lectures 6.5 hours

A To Z Mentor

Video

React for Absolute Beginners

40 Lectures 4.5 hours

Eduonix Learning Solutions

Video

React and Redux: Learn By Building Real World Projects

56 Lectures 12.5 hours

Eduonix Learning Solutions

Video

Step By Step React Native Hybrid Mobile App With Spring Boot

62 Lectures 4.5 hours

Senol Atac

Video

React Full Stack Web Development With Spring Boot

67 Lectures 4.5 hours

Senol Atac

Advertisements