useDrawer
Reads the enclosing Drawer's close handler from any component composed inside it, without prop-drilling a close callback down through the tree.
Overview
useDrawer() reads a close handler from React context, provided by the nearest enclosing
<Drawer>. Call it from any component rendered inside that
<Drawer> — a plain Button in a DrawerFooter, custom body content — instead of threading a
close callback down through props from wherever visible/onClose are managed.
Outside a <Drawer>, useDrawer() 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
The footer button below closes the drawer by calling close from useDrawer(), not by receiving
it as a prop from the component managing visible.
import { useState } from 'react'
import {
Button,
Drawer,
DrawerBody,
DrawerFooter,
DrawerHeader,
DrawerTitle,
useDrawer
} from '@chassis-ui/react'
const Footer = () => {
const { close } = useDrawer()
return (
<DrawerFooter>
<Button color="primary" onClick={close}>
Done
</Button>
</DrawerFooter>
)
}
export const Example = () => {
const [visible, setVisible] = useState(false)
return (
<>
<Button onClick={() => setVisible(true)}>Open drawer</Button>
<Drawer placement="end" visible={visible} onClose={() => setVisible(false)}>
<DrawerHeader>
<DrawerTitle>Drawer title</DrawerTitle>
</DrawerHeader>
<DrawerBody>
The "Done" button below closes this drawer via <code>useDrawer()</code>, not a prop passed
down from the parent.
</DrawerBody>
<Footer />
</Drawer>
</>
)
}API
useDrawer
function useDrawer(): { close: () => void }useDrawer takes no arguments. Its return value is a single close function that requests the
enclosing <Drawer> 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.