2.0.6 • Published 3 years ago

@rexlabs-spicerhaart/toast v2.0.6

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

Toast

A simplistic Toasts component, that can either handle toasts via redux or via HOCs that store the logic in local state. The rendering of the toasts is handled via portals.

Usage

Redux

With redux all toasts are stored as plain texts in the store and will be rendered in the <ToastPortal />, that can be placed anywhere in the app! You can also place multiple portals and target them by their name:

import { ToastTarget, show } from '@rexlabs/toast';

class Example extends React.Component {
  componentDidMount () {
    setTimeout(() => {
      open({
        text: 'This is awesome!', // text content of the toast
        isClosable: true, // weather or not to show close button
        duration: 5000, // in ms, 0 = does not automatically close!
        restartTimeoutOnHover: true, // weather or not to restart duration timer on hover
        action: { // include if you wish to dispatch a redux action from the toast
          label: 'Click me!', // action's clickable text
          reduxAction: {
            type: 'REDUX_ACTION_TYPE', // redux action's type
            payload: { id: 420 } // redux action's payload
          }
        }
      });
    })
  }
  
  render () {
    return (
      <div>
      	<p>Hello World</p>
        <ToastTarget />
      </div>
    )
  }
}

/*****************
 * app.js
 *****************/

import { ToastProvider } from '@rexlabs/toast';

class App extends React.Component {
  render () {
    return (
      <Provider store={store}>
        <ToastProvider {...defaultOptions}>
      	  {children}
        </ToastProvider>
      </Provider>
    );
  }
}

/*****************
 * store.js
 *****************/

import { toastReducer as toasts } from '@rexlabs/toasts';

export const store = createStore(
  combineReducers({ toasts })
)

Example with multiple targets:

import { ToastTarget, show } from '@rexlabs/toast'

class Example extends React.Component {
  componentDidMount () {
    setTimeout(() => {
      // Define target in action!
      show({ target: 'bottom', text: 'This is awesome!' });
      setTimeout(() => {
        open({ target: 'topLeft', text: 'This is also awesome!' });
      }, 5000)
    }, 2000)
  }
  
  render () {
    // All targets must have unique names!
    return (
      <div>
      	<p>Hello World</p>
        <ToastTarget name="bottom" />
        <ToastTarget name="topLeft" />
      </div>
    )
  }
}

HOC

Alternatively you might need to deal with more complex toasts, that e.g. have undo action handlers etc. attached to them, which would not be ideal to be stored in redux. For this scenario there is a HOC provided, that abstracts out the core logic of the toast handling and lets you define the toast manually.

import { ToastTarget, ToastPortal, withToast } from '@rexlabs/toast';

class App extends React.Component {
  render () {
    return (
      <div>
      	<p>Hello World</p>
        <ToastTarget name="myToasts" />
      </div>
    )
  }
}

@withToast({ propName: 'testToast', ...defaultOptions })
class Example extends React.Component {
  componentDidMount () {
    const { testToast } = this.props;
    testToast.show({
      data: { x: 'Test' },
      ...overrideOptions 
    });
  }
  
  render () {
    return (
      <div>
      	<p>Some content</p>
        {testToast.isVisible && (
          <ToastPortal target='myToasts'>
            <div {...testToast.eventHandlers}>
              <p>This is my toast content</p>
              <p>With custom data: {testToast.data.x}</p>
              <button onClick={testToast.hide}>Close toast</button>
              <button onClick={doMagic}>Magic</button>
            </div>
          </ToastPortal>
        )}
      </div>
    );
  }
}

API

ToastProvider

When using toasts with redux, this provider handles the actual rendering of the toasts from the redux store into the specified portal targets. The props provided to the provider will be used as default for all toasts.

Props:

  • Toast (optional) — optional Toast component to be used instead of the default component
  • …openArgs (all optional) — see open API

ToastTarget

Basically just a <PortalTarget /> with a proper default name. Lets you place the toast container anywhere in the app.

Props:

  • name (optional) — unique name within the app
  • …openArgs (all optional) — see open API

Usage:

import { ToastTarget } from '@rexlabs/toast';
<ToastTarget name='customName' />

show

Redux action creator to open a toast.

Args (object):

  • text — string or element that should be displayed as the toast content
  • duration (optional) — in ms, 0 = does not hide automatically!
  • isClosable (opional, default = true) — weather or not to show the close button in the default tooltip
  • target (optional, default = "toasts") — name of target portal this toast should be rendered in

Usage:

import { open } from '@rexlabs/toast';
open({
  text: 'Some test toast!'
});

hide

Redux action to hide a given toast.

Args (object):

  • id — id of the toast to be hidden

Usage:

import { hide } from '@rexlabs/toast';
hide({ id: 1 });\

toastsReducer

Reducer to be added to the store that handles the toasts state for the app.

Usage:

import { toastsReducer as toasts } from '@rexlabs/toast';
const reducers = combineReducers({ toasts });

withToast

HOC that handles all toast specific logic for you in internal state rather than redux. Allows you to have more complex functionality on the (rendering of the) toast itself.

Args:

  • propName (optional, default = "toast") — the name of the prop that the HOC will pass down
  • …openArgs (all optional) — see open API

Props provided by the HOC:

  • show — function to show toast
  • close — function to close the toast manually
  • eventHandlers — contains the onMouseOver and onMouseOut event handlers that deal with the timer logic
  • isVisible — weather or not the toast is currently visible

Development

Install dependencies

$ yarn

Available Commands

$ yarn start              # starts storybook, for visually testing toast
$ yarn test               # runs all units tests
$ yarn test:watch         # runs unit tests when files change
$ yarn build              # bundles the package for production

Legal

Copyright © 2018 Rex Software All Rights Reserved.