1.0.0 • Published 3 years ago

@ehynds/react-toast v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

react-toast

build status

A deliberately minimal React toast component with an imperative API.

Installation

$ npm install --save @ehynds/react-toast

# or

$ yarn add @ehynds/react-toast

Usage

import { ToastProvider, useToast } from '@ehynds/react-toast';

// Somewhere up high in the tree
const App = () => (
  <ToastProvider>
    <SomeComponent />
  </ToastProvider>
);

const SomeComponent = () => {
  const toast = useToast();

  const onClick = () => {
    toast.success('It worked!');

    // OR:
    // toast.error('Error toast');
    // toast.info('Info toast');
  };

  return <a onClick={onClick}>Show a "success" toast</a>;
};

Options

Pass containerOptions to customize the element toasts are rendered into, and pass toastOptions to set defaults for all rendered toasts.

const containerOptions: Partial<ContainerOptions> = {
  className: 'toast-container'
};

const defaultToastOptions: Partial<ToastOptions> = {
  position: 'top-right
};

<ToastProvider
  containerOptions={containerOptions}
  toastOptions={defaultToastOptions}
/>

You can also pass ToastOptions into each toast individually:

const { success } = useToast();

success('It worked!', { autoHide: false });

Container Options

OptionDescriptionDefault
targetA reference to an Element where toasts will be rendered intodocument.body
classNameA class name to attach to the containerNone
styleAn object of CSS properties to attach to the containerNone

Toast Options

OptionDescriptionDefault
autoHideWhether or not each toast should automatically disappear after autoHideDuration secondstrue
autoHideDurationHow long (in seconds) until toasts disappear5000
positionWhere should toast appear? One of: top-left, top-center, top-righttop-center
onClickA handler to capture clicks on the toast. The handler receives an object as its only argument with a dismiss function to dismiss the toast.None
classNameA class name to attach to the toastNone
styleAn object of CSS properties to attach to the toastNone

Recipes

Dismiss a toast on click

const { success } = useToast():

success('Click me to dismiss', {
  onClick: ({ dismiss }) => dismiss()
});