Toast

Toasts provide brief messages about application state.

Overview

Toasts overlay the application screen and sit fixed relative to the viewport.

Usage

By default, a Toast will remain visible until dismissed. The user can dismiss it by tapping/clicking anywhere outside of it.

Basic Usage

Wrap your app in the ToastProvider, which provides context for the Toast descendants.

import { ToastProvider, useToasts } from '@royalnavy/react-component-library'

const FormWithToasts = () => {
  const { addToast } = useToasts()

  const onSubmit = async value => {
    const { error } = await dataPersistenceLayer(value)

    if (error) {
      addToast(error.message, { appearance: 'error' })
    } else {
      addToast('Saved Successfully', { appearance: 'success' })
    }
  }

  return <form onSubmit={onSubmit}>...</form>
}

const App = () => (
  <ToastProvider>
    <FormWithToasts />
  </ToastProvider>
)

Hook

The useToast hook has the following signature:

const { 
  addToast, 
  removeToast, 
  removeAllToasts, 
  updateToast, 
  toastStack 
} = useToasts()

The addToast method has three arguments:

  1. The first is the content of the toast, which can be any renderable Node.
  2. The second is the Options object, which can take any shape you like. Options.appearance is required when using the DefaultToast. When departing from the default shape, you must provide an alternative, compliant Toast component.
  3. The third is an optional callback, which is passed the added toast ID.

The removeToast method has two arguments:

  1. The first is the ID of the toast to remove.
  2. The second is an optional callback.

The removeAllToasts method has no arguments.

The updateToast method has three arguments:

  1. The first is the ID of the toast to update.
  2. The second is the Options object, which differs slightly from the add method because it accepts a content property.
  3. The third is an optional callback, which is passed the updated toast ID.

The toastStack is an array of objects representing the current toasts, e.g.

[
  { content: 'Something went wrong', id: 'generated-string', appearance: 'error' },
  { content: 'Item saved', id: 'generated-string', appearance: 'success' }
]

ToastProvider Props

NameTypeRequiredDefaultDescription
childrenstringTruen/aMain content displayed by the toast.
autoDismissTimeoutnumberFalse5000The time until a toast will be dismissed automatically, in milliseconds.
placementPlacementTypeFalsetop-rightWhere, in relation to the viewport, to place the toasts.
transitionDurationnumberFalse220The duration of the CSS transition on the Toast component.