Don't close Dialog(Modal) when click outside in React & HeadlessUI

Viewed 6142

my problem is simple ... I'm using HeadlessUI's Dialog component for React in my app and when I click out of modal I wish it wouldn't close. In the documentation, there is the Dialog. Overlay parameter that deals with this interaction but there are no settings to disable it.

Any solutions? This is the link to the HeadlessUI docs of the component I am using: https://headlessui.dev/react/dialog

Maybe did u know the kind of "Alert blocking modal" for React??

5 Answers

You can remove the onClose={closeModal} from Dialog and instead pass the closeModal function to onClick handler of any button in the example from the link that you have provided:

<Dialog
  as="div"
  className="fixed inset-0 z-10 overflow-y-auto" // removed onClose
>

Instead pass it to a close button inside the dialog

<button onClick={handleClose}>Close</button>

Add return empty object in onClose function of Dialog UI. here is my code:

 <Dialog
    initialFocus={completeButtonRef}
    as='div'
    className='fixed inset-0 z-10 overflow-y-auto'
    onClose={() => {}}
    open={false}
  >

I had the same problem with https://headlessui.dev/react/dialog ReactJS and Typescript

I fixed passing a new prop called onClose(value: boolean): void; where i can handle the state outside the component onClose={() => {setIsOpen(false) }} and in the Dialog calling the prop onClose={onClose}

Part 1

   <Transition appear show={showModal} as={Fragment}>
        <Dialog
          as="div"
          className={clsx("fixed inset-0 z-50 overflow-y-auto", 
          className)}
          onClose={onClose}
        > 

....

Part 2enter code here

   <Modal
        {...args}
        showModal={isOpen}
        onClose={() => {setIsOpen(false) }}
      />
onClose={() => null }>

you can also return null, it prevents the outside click!

Related