ReactNode
Snackbar
The snackbar component is used to give feedback after certain actions.
The snackbar is used to show alerts on top of an overlay. The snackbar will close itself when the close button is clicked, or after a timeout — the default is 5 seconds.
Snackbars can be configured to appear at either the top or the bottom of an application window, and it is possible to have more than one snackbar onscreen at a time.
Import#
import { useSnackbar } from '@saas-ui/react'
Usage#
function SnackbarExample() {const snackbar = useSnackbar()return (<ButtononClick={() =>snackbar({title: 'Account created.',description: "We've created your account for you.",status: 'success',duration: 9000,isClosable: true,})}>Show Snackbar</Button>)}
Make sure to call
useSnackbar
at least one component level below the<SaasProvider>
or<ChakraProvider>
because it needs access to the current theme.
Convenience methods#
Snackbar adds a bunch of convenience methods on top of the default useToast hook.
You can either pass a snackbar options object or simply a string, which is a shorthand for {title: '...'}
function SnackbarExample() {const snackbar = useSnackbar()return (<HStack spacing={4}><Button onClick={() => snackbar.info('Your account has been created.')}>Show Info</Button><ButtononClick={() => snackbar.success('Your account has been created.')}>Show Success</Button><ButtononClick={() => snackbar.error("Your account couldn't be created.")}>Show Error</Button><ButtononClick={() =>snackbar.promise(new Promise((resolve) => setTimeout(resolve, 10000)),{loading: 'Creating your account...',success: 'Your account has been created.',error: "Your account couldn't be created.",})}>Show Promise</Button></HStack>)}
Action#
function SnackbarExample() {const snackbar = useSnackbar()return (<ButtononClick={() =>snackbar.success({title: 'Email sent',description: 'The email has been sent',action: <Button variant="subtle">Undo</Button>,})}>Show Snackbar</Button>)}
Custom component#
Display a custom component instead of the default Snackbar UI.
function CustomSnackbarExample() {const snackbar = useSnackbar()return (<ButtononClick={() =>snackbar({position: 'bottom-left',render: () => (<Box color="white" p={3} bg="blue.500">Hello World</Box>),})}>Show Snackbar</Button>)}
Closing Snackbars#
Snackbars can be closed imperatively, individually (via the close
instance
method) or all together (via the closeAll
instance method).
function ClosingSnackbarExample() {const snackbar = useSnackbar()const snackbarIdRef = React.useRef()function close() {if (snackbarIdRef.current) {snackbar.close(snackbarIdRef.current)}}function closeAll() {// you may optionally pass an object of positions to exclusively close// keeping other positions opened// e.g. `{ positions: ['bottom'] }`snackbar.closeAll()}function addSnackbar() {snackbarIdRef.current = snackbar({ description: 'some text' })}return (<Stack isInline spacing={2}><Button onClick={addSnackbar} type="button">Snackbar</Button><Button onClick={close} type="button" variant="outline">Close last snackbar</Button><Button onClick={closeAll} type="button" variant="outline">Close all snackbars</Button></Stack>)}
Updating Snackbars#
Snackbars' options can be updated, by passing an id
and the new options
to the
update
instance method.
function UpdatingSnackbarExample() {const snackbar = useSnackbar()const snackbarIdRef = React.useRef()function update() {if (snackbarIdRef.current) {snackbar.update(snackbarIdRef.current, { description: 'new text' })}}function addSnackbar() {snackbarIdRef.current = snackbar({ description: 'some text' })}return (<Stack isInline spacing={2}><Button onClick={addSnackbar} type="button">Snackbar</Button><Button onClick={update} type="button" variant="outline">Update last snackbar</Button></Stack>)}
Status#
You can use status
to change the color of your snackbars.
function SnackbarStatusExample() {const snackbar = useSnackbar()const statuses = ['success', 'error', 'warning', 'info']return (<Wrap>{statuses.map((status, i) => (<WrapItem key={i}><ButtononClick={() =>snackbar({title: `${status} snackbar`,status: status,isClosable: true,})}>Show {status} snackbar</Button></WrapItem>))}</Wrap>)}
Variants#
If you're using the Saas UI theme, Snackbar will automatically use the snackbar
variant by default.
You can also use variants of the
Alert
component.
function SnackbarVariantsExample() {const snackbar = useSnackbar()const variants = ['snackbar', 'solid', 'subtle', 'left-accent', 'top-accent']return (<Wrap>{variants.map((variant, i) => (<WrapItem key={i}><ButtononClick={() =>snackbar({title: `${variant} snackbar`,variant: variant,isClosable: true,})}>Show {variant} snackbar</Button></WrapItem>))}</Wrap>)}
Custom container styles#
The snackbar
function now exposes a containerStyle
property you can use to
override the default styles for the snackbar container.
function Example() {// Via instantiationconst snackbar = useSnackbar({position: 'top',title: 'Container style is updated',containerStyle: {width: '800px',maxWidth: '100%',},})// Or via trigger// Style here will overwrite the entire style abovereturn (<ButtononClick={() => {snackbar({containerStyle: {border: '20px solid red',},})}}>Click me to show snackbar with custom container style.</Button>)}
Changing the snackbar position#
Using the position
prop you can adjust where your snackbar will be popup from.
function PositionExample() {const snackbar = useSnackbar()const positions = ['top','top-right','top-left','bottom','bottom-right','bottom-left',]return (<Wrap>{positions.map((position, i) => (<WrapItem key={i}><ButtononClick={() =>snackbar({title: `${position} snackbar`,position: position,isClosable: true,})}>Show {position} snackbar</Button></WrapItem>))}</Wrap>)}
Preventing Duplicate Snackbar#
In some cases you might need to prevent duplicate of specific snackbars. To achieve
you need to pass an id
and use the snackbar.isActive
method to determine when
to call snackbar(...)
.
function PreventDuplicateExample() {const snackbar = useSnackbar()const id = 'test-snackbar'return (<ButtononClick={() => {if (!snackbar.isActive(id)) {snackbar({id,title: 'Hey! You can create a duplicate snackbar',})}}}>Click me!</Button>)}
Props#
action
action
colorScheme
colorScheme
Color Schemes for useSnackbar
are not implemented in the default theme. You can extend the theme to implement them.
"whiteAlpha" | "blackAlpha" | "gray" | "red" | "orange" | "yellow" | "green" | "teal" | "blue" | "cyan" | "purple" | "pink" | "linkedin" | "facebook" | "messenger" | ... 6 more ...
containerStyle
containerStyle
Optional style overrides for the container wrapping the toast component.
StyleProps
description
description
The description of the toast
ReactNode
duration
duration
The delay before the toast hides (in milliseconds)
If set to null
, toast will never dismiss.
number | null
5000 ( = 5000ms )
icon
icon
A custom icon that will be displayed by the toast.
ReactNode
id
id
The id
of the toast.
Mostly used when you need to prevent duplicate.
By default, we generate a unique id
for each toast
ToastId
isClosable
isClosable
If true
, toast will show a close button
boolean
onCloseComplete
onCloseComplete
Callback function to run side effects after the toast has closed.
(() => void)
position
position
The placement of the toast
ToastPosition
"bottom"
render
render
Render a component toast component.
Any component passed will receive 2 props: id
and onClose
.
((props: RenderProps) => ReactNode)
size
size
ResponsiveValue<string & {}>
status
status
The status of the toast.
"info" | "warning" | "success" | "error" | "loading"
title
title
The title of the toast
ReactNode
variant
variant
string
Was this helpful?