Make the RBSheet reusable as a widget React-Native

Viewed 1560

I am using RBSheet Package for showing up the bottom sheet in my project. I have understood the concept of how to use it from the documentation. Is there a way that I can make the bottom sheet reusable like a Widget? I have tried doing this:

BottomSheetComponent.js

const BottomSheet = ({ message, buttonText }) => {
    // to open this sheet as soon as someone call this Component
    this.RBSheet.open();
    
    return(
        <RBSheet ref={ ref => { this.RBSheet = ref; }} 
            customStyles={{mask: { backgroundColor: COLORS.dark }, container: { elevation: 100 }}}>
            <View style={styles.messageContainer}>
               {/*  Add more data later */}
            </View>
        </RBSheet>
    );
}

export default BottomSheet;

MainComponent.js

const MainComponent = () => {
   const bottomSheet = () => {
      // Trying to call the bottom sheet here
      <BottomSheet />
   }

   return(
     <View>
        <Button onPress={() => bottomSheet()} title="Bottom Sheet" />
     </View>
   );
}

export default MainComponent;

I have failed to get the bottom sheet. I have just started working on React Native. I don't want to go with the generic way which is explained in the Package's docs, it is not a good practice to make the same bottom sheet in two different pages from scratch.

2 Answers

So, after a lot of research, I finally figured out what I was doing wrong.

  • I was using it for the Class Component, although I was using Functional Component
  • The reference was missing, for which, Metro Build Runner, was giving me errors.

Solution

To solve the issue:

  • I need to create my own reference
  • Pass it to the ref props of the Package

MainComponent.js

import React, { useRef } from 'react';

const MainComponent = () => {
   
   // To be used for the reference for the bottom sheet
   const sheetRef = useRef();

   const bottomSheet = () => {
      // Here how you open the bottom sheet right
      sheetRef.current.open();
   }

   return(
     <View>
        <Button onPress={() => bottomSheet()} title="Bottom Sheet" />

        {/* Passing the sheet ref for the binding */}
        <BottomSheet sheetRef={sheetRef} />
     </View>
   );
}

export default MainComponent;

BottomSheet.js

const BottomSheet = ({ sheetRef }) => {
    
    return(
        {/* This is the place to make it work */}
        <RBSheet ref={sheetRef} 
            customStyles={{mask: { backgroundColor: COLORS.dark }, container: { elevation: 100 }}}>
            <View style={styles.messageContainer}>
               {/*  Add more data later */}
            </View>
        </RBSheet>
    );
}

export default BottomSheet;

Can you try this?

const bottomSheet = () => {
  // Trying to call the bottom sheet here
  return <BottomSheet />;
}
Related