useModal
Reads the enclosing Modal's close handler from any component composed inside it, without prop-drilling a close callback down through the tree.
Overview
useModal() reads a close handler from React context, provided by the nearest enclosing
<Modal>. Call it from any component rendered inside that
<Modal> — a plain Button in a ModalFooter, a link inside ModalBody, anything — instead of
threading a close callback down through props from wherever visible/onClose are managed.
Outside a <Modal>, useModal() returns a no-op close rather than throwing, so a component that
calls it doesn't have to guard against rendering outside one.
Basic usage
Both footer buttons below close the modal by calling close from useModal(), not by receiving
it as a prop from the component managing visible.
import { useState } from 'react'
import {
Button,
Modal,
ModalBody,
ModalFooter,
ModalHeader,
ModalTitle,
useModal
} from '@chassis-ui/react'
const Footer = () => {
const { close } = useModal()
return (
<ModalFooter>
<Button color="secondary" onClick={close}>
Cancel
</Button>
<Button color="primary" onClick={close}>
Save changes
</Button>
</ModalFooter>
)
}
export const Example = () => {
const [visible, setVisible] = useState(false)
return (
<>
<Button onClick={() => setVisible(true)}>Launch modal</Button>
<Modal visible={visible} onClose={() => setVisible(false)}>
<ModalHeader>
<ModalTitle>Modal title</ModalTitle>
</ModalHeader>
<ModalBody>
Both footer buttons close this modal — via <code>useModal()</code>, not a prop passed down
from the parent.
</ModalBody>
<Footer />
</Modal>
</>
)
}API
useModal
function useModal(): { close: () => void }useModal takes no arguments. Its return value is a single close function that requests the
enclosing <Modal> close, running the same close transition and onClose callback as dismissing
it via the backdrop, the Escape key, or a built-in close control would.