Snackbar

A transient message in a corner of the window, through a Portal.

Demos

For usage examples, visit the component demo page: Snackbar

Import

import { Snackbar } from '@soroush.tech/design-system/Snackbar'

Props

PropTypeDefaultDescription
isOpenboolean-Whether it is shown. Controlled with onClose.
defaultOpenbooleanfalseWhether it is shown at first, when uncontrolled.
onClose(event, reason: 'timeout' | 'clickaway' | 'escapeKeyDown') => void-Fired when it asks to close, with why.
autoHideDurationnumber-How long it stays, in milliseconds. Without it, it stays until closed.
resumeHideDurationnumberhalf of autoHideDurationHow long it stays once the pointer or focus has left it.
message, actionReactNode-The message, and what sits after it - a button.
childrenReactNode-What it holds in place of the message and the action - an Alert.
anchorOrigin{ vertical: 'top' | 'bottom', horizontal: 'start' | 'center' | 'end' }{ vertical: 'bottom', horizontal: 'start' }The corner of the window; start and end swap right to left.
transitionComponentType<TransitionProps>GrowThe transition that shows and hides it. It must tell onExited.
layerkeyof Theme['zOrder']'snackbar'Stacking layer.
containerHTMLElement | (() => HTMLElement | null)document.bodyPortal target.
shape'square' | 'rounded' | 'pill''rounded'The corners: none, the radius of borderRadius, or a full round.
borderRadiuskeyof Theme['radii']theme.defaults.surfaceRadius, else squareThe radius of a 'rounded' snackbar; other shapes ignore it.
bgkeyof Theme['background']'modal'Background.
textColorkeyof Theme['text']theme.defaults.textColor, else 'initial'Text color.
className, data-testidOn the root - the place it sits in.

Closing

Controlled, it never closes on its own: it asks - onClose is told 'timeout', 'escapeKeyDown' or 'clickaway' - and the owner sets isOpen. Uncontrolled, it closes itself on a time out and on Escape, but not on a click away. An owner that does not want a click away to close it ignores that reason.

Customization

theme.components.Snackbar styles the root (the fixed place), the content (the bar), the message and the action. Its defaultProps set anchorOrigin, autoHideDuration, resumeHideDuration and layer, shape, borderRadius, bg and textColor. The snackbar key of theme.zOrder is its layer.

Server rendering

The snackbar is drawn in a Portal, which renders nothing on the server: it is absent from server-rendered and prerendered HTML, and mounts on the client when it opens (on a click, hover, focus or key, or when the app sets it open). One that starts open, by its open prop, is still closed in the static HTML and opens on hydration. Its trigger renders on the server as usual.

Source code

If this page does not answer your question, have a look at the implementation of the component for more detail.