Categories
React Native Answers

How to close React Native modal by clicking on overlay with JavaScript?

Spread the love

Sometimes, we want to close React Native modal by clicking on overlay with JavaScript.

In this article, we’ll look at how to close React Native modal by clicking on overlay with JavaScript.

How to close React Native modal by clicking on overlay with JavaScript?

To close React Native modal by clicking on overlay with JavaScript, we set the visible prop.

For instrance, we write

import React, { useState } from "react";
import {
  Button,
  StyleSheet,
  View,
  TouchableOpacity,
  Modal,
} from "react-native";

const App = () => {
  const [show, setShow] = useState(false);
  return (
    <View>
      <TouchableOpacity style={{ marginTop: 200 }}>
        <Button title="show" onPress={() => setShow(!show)} />
      </TouchableOpacity>
      <Modal transparent={true} visible={show} animationType="slide">
        <TouchableOpacity
          activeOpacity={1}
          style={{ backgroundColor: "#000000aa", flex: 1 }}
          onPress={() => setShow(!show)}
        />

        <View style={{ backgroundColor: "#FFFFFF", flex: 1 }}>
          <View>
            <Button title="close" onPress={() => setShow(!show)} />
          </View>
        </View>
      </Modal>
    </View>
  );
};
export default App;

to set the visible prop to the show state.

If show is true, then the Modal is shown.

Otherwise, it’s hidden.

We call setShow to show the modal in the TouchableOpacity components.

Conclusion

To close React Native modal by clicking on overlay with JavaScript, we set the visible prop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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