react native-tutorial

React Native Modal

When presenting material above an enclosing view, the React Native Modal kind of View component is employed. The three possible modal settings (slide, fade, and none) determine how the modal will appear inside the react native app.

The entire application area is covered by the Modal shown above the screen. We must import Modal from the react-native library in order to use the Modal component in our application.

Example

In ModalExample, logic will be included. By using the toggleModal, we can update the default state. Let us now create a new file: ModalExample.js

We will set the visible property to our modal after updating the initial state by executing the toggleModal. As soon as the state changes, this prop will be updated.

For Android-based devices, the onRequestClose is necessary.

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 and if we click the button, the modal will open.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *