how can I open the modal from another screen?

Viewed 29

I have a modal Reviews in one File with children prop, so when I add my modal Reviews file in a other file how can I open the modal ?

Modal Reviews:

const ParentReviews = ({
  children,
  onPressOpenModal
}: IParentReviews) => {
  const modalReviewsRef = useRef<BottomSheetModal>(null);

  const handleOpenModalReviews = (shop_id: number) => modalReviewsRef.current?.present();
  return (
    <>
      {
        children
      }
      <ModalReviews
        ref={modalReviewsRef}
      />
    </>
  )
}

const s = StyleSheet.create({

});

export default ParentReviews

MainFile.tsx

const Home = () => {

  return (
      <ParentReviews onPressOpenModal={}>
      <ScrollView keyboardShouldPersistTaps='handled' style={s.modalContainer} contentContainerStyle={s.scrollView}>
          <Pressable onPress={}>
            <Text>Open Modal</Text>
          </Pressable>
      </ScrollView>
      </ParentReviews>
  )
});

So how can I run this function When clicking on Open Modal Button on MainFile?

const handleOpenModalReviews = (shop_id: number) => modalReviewsRef.current?.present();

I am very thankful for your help!!

1 Answers

You could declare a boolean state to handle the modal display in the parent component:

const Home = () => {
  const [showModal, setShowModal] = useState<boolean>(false);

  const handleOpenModal = () => setShowModal(true);

  return (
      <ParentReviews showModal={showModal} setShowModal={setShowModal}>
      <ScrollView keyboardShouldPersistTaps='handled' style={s.modalContainer} contentContainerStyle={s.scrollView}>
          <Pressable onPress={}>
            <Text>Open Modal</Text>
          </Pressable>
      </ScrollView>
      </ParentReviews>
  )
});

And use conditional rendering to display/hide the modal component:

const ParentReviews = ({
  children,
  showModal,
  setShowModal,
}: IParentReviews) => {
  const handleCloseModal = () => setShowModal(false);
  return (
    <>
      {children}
      {showModal && <ModalReviews />}
    </>
  );
};

You will need to modify the IParentReviews interface and add:

interface IParentReviews {
    ...
    showModal: boolean;
    setShowModal: React.Dispatch<React.SetStateAction<boolean>>;
}
Related