How to Make Modal Close Automatically in React Native?

Nov 22, 2022 . Admin

This post will give you an example of closing the modal automatically in react native. step by step explain how to make a modal in react native. you will learn how to set time modal close in react native. you can understand the concept of set timeout set model in react native.

In this example, we will create to modal close in automatically in react native.you can modal visible variable set to setTimeout in react native app.below's this example.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React, {useState} from 'react';
import {Modal, Text, TouchableHighlight, View} from 'react-native';

const App = () => {
  const [modalVisible, setModalVisible] = useState(false);

  const showModal = () => {
    setModalVisible(true);
    setTimeout(() => {
      setModalVisible(false);
    }, 5000);
  };

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: 'white',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      <Modal
        animationType="slide"
        transparent
        visible={modalVisible}
        onRequestClose={() => {
          console.log('Modal has been closed.');
        }}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            backgroundColor: 'gray',
            justifyContent: 'center',
            margin: 25,
          }}>
          <Text style={{fontSize: 16, color: 'white'}}>
            This modal will close in Five Seconds..
          </Text>
        </View>
      </Modal>

      <TouchableHighlight
        onPress={() => {
          showModal();
        }}>
        <Text>Show Modal</Text>
      </TouchableHighlight>
    </View>
  );
};

export default App;
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native