react-nativereact-navigationbottom-sheet

Bottom Sheet doesn't close when navigating to different screen


I'm new to programming and when I navigate to the new screen and the bottom sheet doesn't close here's the picture of it. I'm using @gorhom/bottom-sheet^4.I have done some research and I know that using useFocusEffect could acheive it but i dont really know how. Can someone help me on this?

<BottomSheetModal
    enablePanDownToClose={true}
    ref={bottomSheetModalRef}
    index={0}
    snapPoints={snapPoint}
    backdropComponent={renderBackdrop}
  >
    <View>
      <TouchableWithoutFeedback
        onPress={() => {
          navigation.navigate("Settings");
        }}
      >
        <Text style={styles.modalText}>Settings</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback
        onPress={() => {
          navigation.navigate("Saved");
        }}
      >
        <Text style={styles.modalText}>Saved</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback
        onPress={() => {
          navigation.navigate("Delete");
        }}
      >
        <Text style={styles.modalText}>Delete</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback onPress={() => {}}>
        <Text style={styles.modalText}>Log out</Text>
      </TouchableWithoutFeedback>
    </View>
  </BottomSheetModal>

Solution

  • There are few ways to do it. Here are two:

    1. Add useFocusEffect that runs when your screen with BottomSheetModal is unfocused:
    useFocusEffect(
      React.useCallback(() => {
        return () => bottomSheetRef.current?.close()
      }, [])
    );
    
    1. Close BottomSheetModal, whenever you are leaving your screen. In order to do that, you have to call bottomSheetModalRef.current?.close while navigating:

      <TouchableWithoutFeedback
       onPress={() => {
         navigation.navigate("Settings");
         bottomSheetModalRef.current?.close();
       }}
      >
       <Text style={styles.modalText}>Settings</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback
       onPress={() => {
         navigation.navigate("Saved");
         bottomSheetModalRef.current?.close();
       }}
      >
       <Text style={styles.modalText}>Saved</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback
       onPress={() => {
         navigation.navigate("Delete");
         bottomSheetModalRef.current?.close();
       }}
      >
       <Text style={styles.modalText}>Delete</Text>
      </TouchableWithoutFeedback>