How can I open BottomSheetModal (@gorhom/bottom-sheet) in different component, using React-Native (Expo)

Viewed 1829

I am using https://gorhom.github.io/react-native-bottom-sheet/.

I was wondering how can I open "BottomSheetModal" in a different file e.g Navbar Component.

This is what my code looks like at the moment to open the Bottom Sheet inside of the same component.

const BottomSheetModal: FC = () => {
  const bottomSheetModalRef = useRef<BottomSheet>(null);

  const snapPoints = useMemo(() => ["25%", "50%"], []);

  const handlePresentModalPress = useCallback(() => {
    bottomSheetModalRef.current?.present();
  }, []);

  return (
    <>
      <Button title="Test" onPress={() => handlePresentModalPress()} />
      <BottomSheet
        index={1}
        style={{ ...shadows.bottomSheet }}
        ref={bottomSheetModalRef}
        snapPoints={snapPoints}>
        <View style={styles.container}>
          <Text>Awesome </Text>
        </View>
      </BottomSheet>
    </>
  );
};

So how can I use the opening code of the Bottom Sheet inside of my Navbar Component?

Navbar Component:

 // Open BottomSheet here
            <TouchableWithoutFeedback onPress={() => openBottomSheet()}>
              <View>
                <Image
                  style={styles.avatar}
                  source={{
                    uri: "https://lumiere-a.akamaihd.net/v1/images/character_themuppets_kermit_b77a431b.jpeg?region=0%2C0%2C450%2C450",
                  }}
                />
              </View>
            </TouchableWithoutFeedback>

Thank you!

1 Answers

I found out to do this, incase anyone comes across this question, I'll post it here!

So what you have to do is pass the ref to the bottom sheet component. So in the Navbar component I created the ref for the bottom sheet, and then passed it into the bottom sheet.

Navbar:

// Create Ref
const userBottomSheetRef = useRef<BottomSheetModal>(null);

// Pass ref into the bottom sheet component
<BottomSheet ref={userBottomSheetRef} snapPoints={["30%"]}/>

Then inside the bottom sheet component you forward the ref using a react function, and then pass it in as normal:

 <BottomSheetModal ref={ref} >
    <BottomSheetScrollView>
      <View style={styles.container}>{children}</View>
    </BottomSheetScrollView>
  </BottomSheetModal>
Related