A ToastContainer renders the queued toasts in an application. It should be placed at the root of the app.
placement
Actions
Use the actionLabel and onAction options to add an action button to the toast. Set shouldCloseOnAction to true to close the toast when the user presses the button.
import {Button} from '@react-spectrum/s2/Button';
import {ToastQueue} from '@react-spectrum/s2/Toast';
<Button
onPress={() => ToastQueue.info('An update is available', {
actionLabel: 'Update',
onAction: () => alert('Updating!'),
shouldCloseOnAction: true
})}>
Show actionable toast
</Button>
Dismissal
Use the timeout option to automatically hide a toast after a delay. For accessibility, toasts have a minimum timeout of 5 seconds, and actionable toasts will not auto dismiss. Timers will pause when the user focuses or hovers over a toast.
import {Button} from '@react-spectrum/s2/Button';
import {ToastQueue} from '@react-spectrum/s2/Toast';
<Button
onPress={() => ToastQueue.positive('Toast is done!', {
timeout: 5000
})}>
Show auto-dismissing toast
</Button>
Programmatic dismissal
Use the close function returned by ToastQueue to programmatically dismiss a toast that is no longer relevant. The onClose event is triggered when a toast is dismissed, either by user action or programmatically.
import {Button, Text} from '@react-spectrum/s2/Button';
import {ToastQueue} from '@react-spectrum/s2/Toast';
import {useState} from 'react';
function Example() {
let [close, setClose] = useState<(() => void) | null>(null);
return (
<Button
onPress={() => {
if (!close) {
let close = ToastQueue.negative('Unable to save', {
onClose: () => setClose(null)
});
setClose(() => close);
} else {
close();
}
}}>
<Text>{close ? 'Hide Toast' : 'Show Toast'}</Text>
</Button>
);
}
API
ToastContainer
| Name | Type | Default |
|---|---|---|
placement | ToastPlacement | Default: 'bottom'
|
Placement of the toast container on the page. | ||
ToastQueue
neutral | ||
| Queues a neutral toast. | ||
positive | ||
| Queues a positive toast. | ||
negative | ||
| Queues a negative toast. | ||
info | ||
| Queues an informational toast. | ||
Toast Options
| Name | Type | |
|---|---|---|
actionLabel | string | |
A label for the action button within the toast. | ||
shouldCloseOnAction | boolean | |
Whether the toast should automatically close when an action is performed. | ||
timeout | number | |
A timeout to automatically close the toast after, in milliseconds. | ||