useToast
Reads the enclosing Toast's dismiss handler from any component composed inside it, without prop-drilling a close callback down through the tree.
Overview
useToast() reads a close handler from React context, provided by the nearest enclosing
<Toast>. Call it from any component composed inside that
<Toast> — a link inside ToastBody, a custom icon in ToastHeader — instead of threading a
close callback down through props from wherever visible/onVisibleChange are managed.
<Toast>'s own footer prop already hands close directly to a function passed there, which
covers the common case of a footer action closing the toast. Reach for useToast() instead when
the element that should close the toast lives outside footer — anywhere else in the toast's
composed markup.
Outside a <Toast>, useToast() 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 "Undo" link below, composed inside ToastBody rather than passed through footer, closes the
toast by calling close from useToast().
import { useState } from 'react'
import { Button, Toast, ToastBody, ToastHeader, useToast } from '@chassis-ui/react'
const Body = () => {
const { close } = useToast()
return (
<ToastBody>
File deleted.{' '}
<Button variant="link" className="p-0" onClick={close}>
Undo
</Button>
</ToastBody>
)
}
export const Example = () => {
const [visible, setVisible] = useState(true)
return (
<Toast visible={visible} onVisibleChange={setVisible} autohide={false}>
<ToastHeader closeButton>Chassis</ToastHeader>
<Body />
</Toast>
)
}API
useToast
function useToast(): { close: () => void }useToast takes no arguments. Its return value is a single close function that requests the
enclosing <Toast> close, running the same close transition and onClose callback as dismissing
it via auto-hide or a built-in close control would.