Skip to content

react-cooked-breadtoasts

Consumer

All consumers must be descendants of the provider.

With less boilerplate and a succinct readability, the hook is the recommended way to consume the Toast Context Props. If you're new to hooks, consider this introduction to hooks. The following consumption methods may be considered aging patterns.

Higher-Order Component

The higher-order component withToastContext provides toastContext as a Context Props object to your component.

import { withToastContext, WithToastContextProps } from 'react-cooked-bread'

const Component: React.FC<WithToastContextProps> = ({ toastContext }) => {
  const { addToast } = toastContext
  useEffect(async () => {
    try {
      const res = await fetch()
      if (res.ok) {
        addToast('Success')
      }
    } catch (err) {
      addToast('Oops!', {
        type: 'error',
      })
    }
  }, [])

  // ...
}

const ComponentWithToast = withToastContext(Component)

Function as a Child

The function as a child component ToastConsumer offers a way to use a render function as a children prop and make use of the Context Props. Some may consider this method an anti-pattern.

import { ToastConsumer } from 'react-cooked-bread'

const Component = () => (
  <ToastConsumer>
    {(context) => (
      <Notifications clear={context.removeAllToasts}>
        {context.toasts.map(({ id, content }) => <div key={id}>{content}</div>)}}
      </Notifications>
    )
  </ToastConsumer>
)
CI
Build
NPM
Release
Bundle