1.0.0 • Published 4 years ago

nois-react-toast v1.0.0

Weekly downloads
2
License
ISC
Repository
github
Last release
4 years ago

React Toast Notifications

A configurable, composable, toast notification system for react.

https://jossmac.github.io/react-toast-notifications

Install

yarn add react-toast-notifications

Use

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

import { ToastProvider, useToasts } from 'react-toast-notifications'

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>
)

ToastProvider Props

For brevity:

  • PlacementType is equal to 'bottom-left' | 'bottom-center' | 'bottom-right' | 'top-left' | 'top-center' | 'top-right'.
  • TransitionState is equal to 'entering' | 'entered' | 'exiting' | 'exited'.
PropertyDescription
autoDismissTimeout numberDefault 5000. The time until a toast will be dismissed automatically, in milliseconds.
children NodeRequired. Your app content.
components { ToastContainer, Toast }Replace the underlying components.
placement PlacementTypeDefault top-right. Where, in relation to the viewport, to place the toasts.
transitionDuration numberDefault 220. The duration of the CSS transition on the Toast component.

Toast Props

PropertyDescription
appearanceRequired. One of success, error, warning, info
childrenRequired. The content of the toast notification.
autoDismiss booleanDefault: false. Whether or not to dismiss the toast automatically after a timeout. Inherited from ToastProvider if not provided.
autoDismissTimeout numberInherited from ToastProvider.
onDismiss: Id => voidPassed in dynamically.
placement PlacementTypeInherited from ToastProvider.
transitionDuration numberInherited from ToastProvider.
transitionState: TransitionStatePassed in dynamically.

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' }
]

Replaceable Components

To bring each toast notification inline with your app, you can provide alternative components to the ToastProvider:

import { ToastProvider } from 'react-toast-notifications';

const MyCustomToast = ({ appearance, children }) => (
  <div style={{ background: appearance === 'error' ? 'red' : 'green' }}>
    {children}
  </div>
);

const App = () => (
  <ToastProvider components={{ Toast: MyCustomToast }}>...</ToastProvider>
);

To customize the existing component instead of creating a new one, you may import DefaultToast:

import { DefaultToast } from 'react-toast-notifications';
export const MyCustomToast = ({ children, ...props }) => (
  <DefaultToast {...props}>
    <SomethingSpecial>{children}</SomethingSpecial>
  </DefaultToast>
);

Alternatives

This library may not meet your needs. Here are some alternative I came across whilst searching for this solution:

acornacceptsacorn-dynamic-importajv-keywordsansi-regexansi-stylesajv-errorsalphanum-sortansi-colorsansi-escapesansi-htmlany-observableanymatchaprobaargparsearr-diffarr-flattenarr-unionarray-differarrifyarray-flattenajvarray-unionasn1.jsarray-uniqarray-uniqueasync-eachbabel-clibabel-code-frameassertbabel-corebabel-generatoratobbabel-helper-builder-binary-assignment-operator-visitorbabel-helper-builder-react-jsxbabel-helper-call-delegateast-typesassign-symbolsasyncbabel-helper-explode-assignable-expressionbabel-helper-define-mapbabel-helper-function-namebabel-helper-get-function-aritybabel-helper-hoist-variablesbabel-helper-optimise-call-expressionbabel-helper-regexbabel-helper-remap-async-to-generatorbabel-helper-replace-supersbabel-helpersbabel-messagesbabel-helper-bindify-decoratorsbabel-plugin-check-es2015-constantsbabel-eslintbabel-helper-explode-classbabel-plugin-syntax-async-functionsbabel-loaderbabel-plugin-syntax-class-propertiesbabel-plugin-emotionbabel-plugin-syntax-async-generatorsbabel-plugin-syntax-exponentiation-operatorbabel-plugin-syntax-class-constructor-callbabel-plugin-syntax-flowbabel-plugin-syntax-jsxbabel-plugin-syntax-object-rest-spreadbabel-plugin-syntax-trailing-function-commasbabel-plugin-syntax-decoratorsbabel-plugin-transform-async-to-generatorbabel-plugin-syntax-dynamic-importbabel-plugin-transform-class-propertiesbabel-plugin-syntax-export-extensionsbabel-plugin-transform-es2015-arrow-functionsbabel-plugin-transform-es2015-block-scopingbabel-plugin-transform-es2015-block-scoped-functionsbabel-plugin-transform-es2015-classesbabel-plugin-transform-es2015-computed-propertiesbabel-plugin-transform-es2015-destructuringbabel-plugin-transform-es2015-duplicate-keysbabel-plugin-transform-es2015-for-ofbabel-plugin-transform-es2015-function-namebabel-plugin-transform-es2015-literalsbabel-plugin-transform-es2015-modules-commonjsautoprefixerbabel-plugin-transform-async-generator-functionsbabel-plugin-macrosbabel-plugin-transform-es2015-object-superbabel-plugin-transform-es2015-parametersbabel-plugin-transform-es2015-modules-amdbabel-plugin-transform-es2015-shorthand-propertiesbabel-plugin-transform-es2015-modules-umdbabel-plugin-transform-es2015-spreadbabel-plugin-transform-es2015-sticky-regexbabel-plugin-transform-es2015-template-literalsbabel-plugin-transform-es2015-unicode-regexbabel-plugin-transform-es2015-typeof-symbolbabel-plugin-transform-exponentiation-operatorbabel-plugin-transform-flow-strip-typesbabel-plugin-transform-object-rest-spreadbabel-plugin-transform-react-display-namebabel-plugin-transform-react-jsxbabel-plugin-transform-strict-modebabel-plugin-transform-regeneratorbabel-plugin-transform-react-jsx-selfbabel-plugin-transform-export-extensionsbabel-preset-envbabel-preset-flowbabel-plugin-transform-react-jsx-sourcebabel-preset-reactbabel-polyfillbabel-plugin-transform-class-constructor-callbabel-preset-stage-2babel-preset-stage-1babel-templatebabel-typesbabel-traversebabylonbabel-registerbabel-plugin-transform-es2015-modules-systemjsbabel-plugin-transform-decoratorsbabel-runtimebabel-preset-es2015batchbalanced-matchbasebase64-jsbabel-preset-stage-3binary-extensionsbig.jsbinaryextensionsbrace-expansionbn.jsboolbasebluebirdbody-parserbonjourbracesbrowserify-rsabrowserify-aesbrowserify-cipherbrorandbrowserify-signbrowserify-zlibbrowserslistbuffer-frombuffer-indexofbrowserify-desbufferbuffer-xorbuiltin-modulesbuiltin-status-codesbytescacheable-requestcall-me-maybecache-basechalkcacachecaniuse-apicamel-casechokidarchownrcaniuse-dbcaniuse-litechardetcamelcasechrome-trace-eventcipher-basecli-spinnersclass-utilsclapcli-cursorclean-csscli-widthclipboardcli-tablecliuiclonecli-truncateclone-responseclone-statsclone-buffercloneable-readablecoacolor-namecode-point-atcolorcolor-convertcommandercolormincolor-stringcolorsconcat-mapcomma-separated-tokenscomponent-emittercommondircollection-visitcompressionconcat-streamcompressibleconvert-source-mapcontent-dispositionconnect-history-api-fallbackcookie-signaturecontent-typeconstants-browserifyconsole-browserifycookiecopy-descriptorcopy-concurrentlycore-jscore-util-iscreate-hashcosmiconfigcreate-hmaccreate-ecdhcreate-react-contextcross-spawncss-loadercss-whatcss-color-namescsstypecrypto-browserifycss-selectcss-selector-tokenizercssesccssnanocyclistdebugdargscssodate-nowdate-fnsdecamelizedateformatdefine-propertiesdeep-equaldefault-gatewaydeldecode-uri-componentdeep-extenddecompress-responsedefine-propertydetect-indentdefineddepddes.jsdetect-conflictdestroydiffdetect-nodedir-globdns-equaldelegatedom-serializerdom-converterdns-txtdns-packetdomhandlerdiffie-hellmandomutilsduplexer3domelementtypedom-helpersdomain-browserduplexifyeditionsejselegant-spinneree-firstelectron-to-chromiumemojis-listencodeurlentitiesellipticenvinfoenhanced-resolveerrnoerrorescape-string-regexpend-of-streames-abstracterror-exescape-htmlesutilses-to-primitiveeslint-visitor-keyseslint-scopeesrecurseesprimaestraverseeventemitter3eventsetagexecaevp_bytestokeyeventsourceexit-hookexpand-bracketsexpand-tildeexpand-rangeexpressfast-globextend-shallowexternal-editorextglobfast-json-stable-stringifyfast-deep-equalfastparsefile-loaderfiguresfaye-websocketfaultfilename-reserved-regexfilenamifyfilenamify-urlfilename-regexfinalhandlerfill-rangefind-rootflattenfind-cache-dirflow-binfirst-chunk-streamfind-upflow-parserflush-write-streamforeachfollow-redirectsfor-ownfor-infs-readdir-recursiveformatforwardedfs.realpathfragment-cachefrom2freshfs-extrafunction-bindfs-write-stream-atomicglobget-caller-filegh-pagesget-streamget-valuegh-gotglob-parentglob-to-regexpgithub-usernameglob-allglob-baseglobal-modulesgraceful-fsglobal-prefixglobbyhas-ansiglobalsgood-listenerhasgrouped-queuegothandle-thinghas-colorhas-flaghas-to-string-tag-xhas-symbol-support-xhas-valuehash-basehas-valueshast-util-parse-selectorhastscripthehash.jshmac-drbghosted-git-infohpack.jshtml-webpack-pluginhome-or-tmphtml-comment-regexhtml-entitieshomedir-polyfillhtmlparser2html-minifierhttp-cache-semanticshttp-deceiverhttp-proxyhttp-errorshumanize-urlhttp-parser-jshttps-browserifyhttp-proxy-middlewareicss-replace-symbolsicss-utilsiconv-liteieee754iferrinflightinheritsimurmurhashindexes-ofignoreimport-localiniinvariantindent-stringindexofinquirerinternal-ipipinterpretinto-streamis-absolute-urlipaddr.jsip-regexis-arrayishinvert-kvis-accessor-descriptoris-date-objectis-callableis-bufferis-binary-pathis-builtin-moduleis-data-descriptoris-finiteis-directoryis-dotfileis-extendableis-descriptoris-fullwidth-code-pointis-extglobis-globis-numberis-path-cwdis-equal-shallowis-objectis-observableis-oddis-path-insideis-path-in-cwdis-posix-bracketis-promiseis-regexis-plain-objectis-retry-allowedis-primitiveis-plain-objis-symbolis-utf8is-scopedis-svgis-streamisarrayis-windowsis-wsljs-tokensisexeisbinaryfilejsescisobjectistextorbinaryjscodeshiftisurljson5js-yamljs-base64json-parse-better-errorsjson-bufferjson-schema-traversekillablejson3jsonfilekeyvlcidkind-ofleblistr-silent-rendererlistrlistr-update-rendererlistr-verbose-rendererload-json-filelodashloader-runnerlocate-pathloader-utilslodash.camelcaselodash.uniqlodash.memoizelog-updatelog-symbolsloglevellonglower-caselowercase-keysloose-envifymamacrolru-cachelowlightmake-dirmap-age-cleanermap-cachemap-visitmath-expression-evaluatormath-randommedia-typermem-fsmd5.jsmerge2micromatchmemmem-fs-editormemory-fsmerge-descriptorsmime-dbmime-typesmimic-fnminimalistic-assertminimatchmethodsminimistmkdirpmimemimic-responsemiller-rabinmsmississippiminimalistic-crypto-utilsmute-streammixin-deepmove-concurrentlymulticast-dnsmultimatchmulticast-dns-service-typesnegotiatornanomatchneo-asyncno-casenice-trynomnomnode-dirnode-libs-browsernode-forgenormalize-package-datanumber-is-nannormalize-pathobject-assignnum2fractionnth-checkobject-keysobject.getownpropertydescriptorsnormalize-rangenpm-run-pathnormalize-urlobject-copyonceobufobject.omitobject.pickobject-visitonetimeon-headerson-finishedos-browserifyoutput-file-syncoraopnoriginalos-homediros-localep-cancelablep-deferp-each-seriesos-tmpdirp-finallyp-lazyp-is-promisep-locatep-limitparallel-transformp-reducep-mapp-timeoutpakop-tryparam-caseparse-globparse-asn1parse-jsonparse-passwdpath-is-absolutepath-dirnamepascalcaseparseurlpath-is-insidepath-browserifypath-to-regexppath-existspath-keypath-parsepath-typepifypbkdf2pinkiepinkie-promisepkg-dirportfinderposix-character-classespostcss-calcpostcss-convert-valuespostcss-colorminpostcsspostcss-discard-commentspostcss-discard-duplicatespostcss-discard-emptypostcss-discard-unusedpostcss-discard-overriddenpostcss-filter-pluginspostcss-merge-identspostcss-merge-rulespostcss-message-helperspostcss-merge-longhandpostcss-minify-font-valuespostcss-minify-paramspostcss-minify-selectorspostcss-minify-gradientspostcss-modules-extract-importspostcss-modules-local-by-defaultpostcss-modules-scopepostcss-modules-valuespostcss-normalize-charsetpostcss-reduce-identspostcss-normalize-urlpostcss-reduce-initialpostcss-ordered-valuespostcss-reduce-transformspostcss-selector-parserpostcss-svgopostcss-unique-selectorspostcss-value-parserprettierpostcss-zindexprivatepretty-errorprepend-httppreserveprocess-nextick-argsprismjspretty-bytespromise-inflightprocessprrprop-typesproperty-informationpumpproxy-addrpseudomappublic-encryptpunycodepumpifyqqsquerystringquery-stringquerystring-es3querystringifyrandomaticrandombytesreactraw-loaderreact-domreact-isreact-syntax-highlighterreact-radiosrandomfillreact-transition-grouprange-parserraw-bodyread-chunkread-pkg-upread-pkgreaddirpregeneraterecastreadable-streamregenerator-transformreduce-css-calcreduce-function-callregjsgenrechoirregenerator-runtimeregjsparserrefractorregex-cacheregex-notrepeatingregexpu-corerenderkidrelateurlremove-trailing-separatorrequire-from-stringrepeat-elementrepeat-stringreplace-extrequire-directoryrequires-portrequire-main-filenameresolveresolve-cwdresolve-dirresolve-fromresponselikeresolve-urlrimrafretrestore-cursorripemd160run-queuerun-asyncsafe-bufferrxjssafe-regexsafer-buffersaxschedulersemverschema-utilsselectscoped-regexselect-hoseselfsignedserialize-javascriptset-blockingsendset-immediate-shimset-valueserve-indexserve-staticsetimmediateslashsha.jsshebang-regexshebang-commandsetprototypeofslideshelljssignal-exitslice-ansisnapdragonsource-mapsnapdragon-nodesnapdragon-utilsource-list-mapsockjssort-keyssockjs-clientsource-map-resolvesource-map-urlspdx-exceptionssource-map-supportspdx-correctspace-separated-tokensspdx-license-idsspdx-expression-parsespdysplit-stringspdy-transportsprintf-jsstatusesssristream-eachstrict-uri-encodestatic-extendstream-browserifystrip-ansistream-httpstream-shiftstring-widthstring-templatestring_decoderstrip-bomstrip-bom-streamstyle-loaderstrip-eofstrip-url-authstrip-outersupports-colorsvgosymbol-observabletemptapabletextextensionsthrough2throughtext-tablethunkytimed-outtimers-browserifytmptiny-emitterto-arraybuffertrimtrim-righttoposortto-fast-propertiesto-object-pathtslibto-regex-rangeto-regextrim-repeatedtty-browserifytype-istypedarrayuglify-jsuglify-esuniqsunique-slugunderscoreuglifyjs-webpack-pluginuniqunique-filenameuniversalifyunset-valueunpipeunion-valueunstatedupathuntildifyurixurluri-jsupper-caseurl-to-optionsurl-parse-laxurl-parseuseutil.promisifyuser-homeutilautilutil-deprecateutils-mergeuuidv8-compile-cachev8flagsvendorsvalidate-npm-package-licensevinylvarywbufwebpackvinyl-filevm-browserifywebpack-cliwebpack-dev-serverwebpack-addonswatchpackwebpack-sourceswebpack-dev-middlewarewebpack-logwebsocket-driverwrappywebsocket-extensionswhet.extendwhichwhich-moduleworker-farmwrap-ansiwrite-file-atomicy18nxregexpxtendyargsyeoman-environmentyeoman-generatoryargs-parserhighlight.js
1.0.0

4 years ago