bash.ruv
bash.ruv

Reputation: 45

react native modal close with swipe down (react-native-swipe-gestures)

I am making a modal opening and closing using the swipe gesture(react-native-swipe-gestures).
But It doesn't work any swipe when Modal is Visible.
I want that Modal can close with swipe down.
Does it any solution?

import React from 'react';
import { ... } from 'react-native';
import GestureRecognizer from 'react-native-swipe-gestures';

export default class SwipeModal extends Component {

 state = {
  modalVisible: false
 }

 setModalVisible = (visible) => {
  this.setState({ modalVisible: visible });
 }

 render() {
  const { modalVisible } = this.state;
  return (
   <View>
    <Modal 
     animationType="slide"
     presentationStyle="formSheet"
     visible={ modalVisible }
    >
     <GestureRecognizer
      onSwipeDown={ () => this.setModalVisible(!modalVisible) }
     >
      <Text>Swipe Down Please</Text>
     </GestureRecognizer>
    </Modal>
    <GestureRecognizer
      onSwipeUp={ () => this.setModalVisible(true) }
     >
      <Text>Swipe Up Please</Text>
     </GestureRecognizer>
   </View>
  )
}

...

Upvotes: 4

Views: 27055

Answers (2)

Talha Javed
Talha Javed

Reputation: 125

no need to use GestureRecognizer.

 function SwipeDownModal() {
  const [isModalVisible, setModalVisible] = useState(false);

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  return (
    <View>
      <TouchableOpacity onPress={toggleModal}>
        <Text>Show Modal</Text>
      </TouchableOpacity>

      <Modal
        isVisible={isModalVisible}
        swipeDirection="down" // Enable swipe down to close the modal
        onSwipeComplete={toggleModal} // Handle swipe down event
        style={styles.modal}
      >
        <View style={styles.modalContent}>
          <Text>This is a swipe-down modal</Text>
          <TouchableOpacity onPress={toggleModal}>
            <Text>Close Modal</Text>
          </TouchableOpacity>
        </View>
      </Modal>
    </View>
  );
}

just add this props swipeDirection="down" and onSwipeComplete={toggleModal}

Upvotes: -2

ShevO27
ShevO27

Reputation: 906

You need to wrap your view inside 1 gesture recognizer, and pass children to it that will have access onSwipe gestures, then you need to give it style={{flex: 1}} so it will cover all screen, like this:

<GestureRecognizer
  style={{flex: 1}}
  onSwipeUp={ () => this.setModalVisible(true) }
  onSwipeDown={ () => this.setModalVisible(false) }
>
  <Modal 
    animationType="slide"
    presentationStyle="formSheet"
    visible={ modalVisible }
  >
    <Text>Swipe Down Please</Text>
  </Modal>
  <Text>Swipe Up Please</Text>
</GestureRecognizer>

Upvotes: 9

Related Questions