How do I close a modal window by clicking on any child link?
import { Dialog } from "@headlessui/react"
const [modalIsOpen, setModalIsOpen] = useState<boolean>(false)
<Dialog open={modalIsOpen} onClose={() => setModalIsOpen(false)}>
<div className="fixed inset-0 overflow-y-auto">
<Dialog.Panel as="div" className="absolute right-5 top-10">
<MobileLkMenu />
</Dialog.Panel>
</div>
</Dialog>
Now the modal window is closed only for a click outside.
Also, if you hang the event handler on Dialog.Panel, the modal window will close when click on its body, but not on the link. How do I make the link close?
Dynamic options are rendered in the modal window (sometimes a large number). There is no way to throw a callback into each option.
There are a few ways to solve this. For a simple example, you can use the
onClosecallback provided by Dialog from@headlessui/react. However, theonClosecallback should be triggered from within the modal content itself, not from theDialog.Panel.Here's how you can modify your code to achieve this:
In this example, clicking on the "Close Modal" link inside the modal content will trigger the
onClickevent, which in turn callssetModalIsOpen(false), closing the modal window.without callbacks / useRef update: