How to Make React Native Modal Close Automatically

We use modals to show alerts, messages, or any other information to the user. As modals are basically dialog boxes displayed over the parent view, it attracts user attention. Hence, modals are an important component in React Native.

In most of the modals, there will be a close button which makes the modal hide when it is pressed. But in this blog post, I will show how to automatically close react native modal without a close button.

To make the modal close automatically, we use the setTimeout method. If you want to know how to use setTimeout method then see this blog post. Let’s go through the react native example given below:

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;

In the react native example, the modal is shown when the touchableHighlight component is pressed. Inside showModal function, we use setTimeout method to show the modal for five seconds, and then the modal is hidden by setting modalVisible false.

The output of the above example is as given below:

react native modal automatic close

That’s how you automatically close modal in react native.

2 thoughts on “How to Make React Native Modal Close Automatically”

Leave a Reply

%d bloggers like this: