Closing a modal in React

The suggested way to close a modal is by toggling a prop to display it, however if you use the backdropDismiss option this will hide the modal, but won’t trigger the method passed to dismiss the modal. How does one close the modal using backdropDismiss and also support closing the modal with a close button?

Edit: I can see there’s a dismiss method, but can’t get access to it, tried using a ref on the modal, but it says dismiss is null.

Here’s some code for reference.

const Modal = ({
  onDidDismiss = () => {},
  onWillDismiss = () => {},
  handleDismiss = () => {},
  hideHeader = false,
  backdropDismiss = true,
}: any) => {
  const { children } = props;
  const [presented, setPresented] = useState(false);
  const componentIsMounted = useRef(true);

  const handleWillPresent = () => {
    if (componentIsMounted.current) setPresented(true);

  return (
      isOpen={componentIsMounted.current && isOpen}
      // onDidPresent={handleDidPresent}
      {!hideHeader && (
        <IonHeader className="bg-white">
            {title && (
              <IonTitle className="text-center">
                <div className="font-serif text-center h4">{title}</div>
              className="absolute right-0 top-0 mr-4 mt-4 md:mr-8 md:mt-3"
              <CloseButton handleDismiss={handleDismiss} />
      <IonContent className="modal-content">
        <div className="modal-content-inner relative w-full">
          {/* Wait to render children, as form refs won't properly register */}
          {presented && children}

in one of you handlers onDidDismiss or onWillDismiss set isOpen to false…

But that would mutate the prop

It doesn’t have to… the parent container should be updating the state

Yeah, that’s what I am doing. Here it is in use:

  handleDismiss={() => setShowUpgrade(false)}


My problem is that I have a close button in the Modal jsx that calls handleDismiss. If I make it so that handleDismiss is also called in the onDidDismiss then I’ll have a double fire. Not good, but I guess not the end of the world if it’s just setting the isOpen prop to false, however if it handles any other logic then that could lead to some undesirable bugs. I guess I could debounce it, not ideal either, but it’d work. If I could just call dismiss using the same method that the background must use then this would be easily avoided :slightly_frowning_face: