Toast

Toast

The Toast component is a hook used to trigger notification push. It manages the display and hiding of notifications in a global state.

General









Step 1. Wrap your app with ToastProvider

First, wrap your application (or the part where you want to use toasts) with ToastProvider:


Show Code
import { ToastProvider } from 'funda-ui/Toast';
 
function App() {
    return (
        <ToastProvider>
            <YourApp />
        </ToastProvider>
    );
}

You can also use a global configuration (Or use toast.updateConfig() to update):


Show Code
import { ToastProvider } from 'funda-ui/Toast';
 
function App() {
    return (
        <ToastProvider config={{
            defaultWrapperClassName: '',
            defaultOnlyShowOne: false,
            defaultDirection: 'bottom-center',
            defaultCascading: false,
            defaultReverseDisplay: false
        }}>
            <YourApp />
        </ToastProvider>
    );
}

Step 2. Use the useToast hook useToast()


Show Code
import React from "react";
import { useToast } from 'funda-ui/Toast';
 
// component styles
import 'funda-ui/Toast/index.css';
 
export default () => {
 
    const toast = useToast();
 
    const showSimpleToast = () => {
        toast.show({
            actionId: 'test-1',
            title: "Success",
            message: <div>Text here ({Math.random()})</div>,
        });
    };
 
    const showCustomToast1 = () => {
        toast.show({
            actionId: 'test-2',
            title: "Custom Toast 1",
            message: <div style={{color: "orange"}}>Text here ({Math.random()})</div>,
            theme: "dark",
            autoCloseTime: 1000
        });
    };
 
 
    const showCustomToast2 = () => {
        toast.show({
            actionId: 'test-3',
            title: "Custom Toast 2",
            message: <><div>Text here ({Math.random()})</div></>,
            theme: "dark",
            autoCloseTime: 5000,
            direction: 'top-center',
            schemeBody: 'align-items-center text-white border-0 p-2',
            closeBtnColor: '#333',
            onClose: (e, currentIndex, displayedElements) => {
                console.log(e, currentIndex, displayedElements);
            }
        });
    };
 
    const showCustomToast3 = () => {
        toast.show({
            actionId: 'test-4',
            note: "11 mins ago", 
            message: <><div style={{fontSize:"14px"}}>This is <span style={{color:"orange"}}>orange</span> text ({Math.random()})</div></>,
            autoCloseTime: 5000,
            cascading: true,
            direction: 'bottom-right',
            reverseDisplay: true
            
        });
    };
 
    const showCustomToast4 = () => {
        toast.show({
            actionId: 'test-5',
            note: "11 mins ago", 
            message: <><div>Text here ({Math.random()})</div></>,
            autoCloseTime: 5000,
            direction: 'vertical-center',
            schemeHeader: 'text-white bg-dark',
            schemeBody: 'align-items-center text-dark border-0 p-2',
            closeBtnColor: '#fff',
            reverseDisplay: true
        });
    };
 
 
    const showCustomToast5 = () => {
        toast.show({
            actionId: 'test-6',
            closeDisabled: true,
            message: <><div>Text here ({Math.random()})</div></>,
            autoCloseTime: 5000,
            direction: 'bottom-left',
            schemeHeader: 'p-0',
            schemeBody: 'align-items-center text-white bg-dark border-0'
        });
    };
 
 
 
    const showCustomToast6 = () => {
        toast.show({
            actionId: 'test-7',
            direction: 'top-center',
            title: "Custom Toast 1",
            message: <div style={{color: "orange"}}>Text here ({Math.random()})</div>,
            theme: "dark",
            autoCloseTime: 3000,
            onlyShowOne: true
        });
    };
 
    const updateToastConfig = () => {
        toast.updateConfig({
            defaultDirection: 'bottom-right',
            defaultOnlyShowOne: true
        });
        alert('Config successfully updated');
    };
 
 
 
    return (
        <>
 
            <button onClick={showSimpleToast}>Basic Toast</button>
            <button onClick={showCustomToast1}>Custom Toast 1</button>
            <button onClick={showCustomToast2}>Custom Toast 2</button>
            <button onClick={showCustomToast3}>Custom Toast 3</button>
            <button onClick={showCustomToast4}>Custom Toast 4</button>
            <button onClick={showCustomToast5}>Custom Toast 5</button>
            <button onClick={showCustomToast6}>Custom Toast 6 (Only one is shown)</button>
            <button onClick={updateToastConfig}>Update Global configuration</button>
          
        </>
    );
}

Toast Management

The useToast() hook provides several methods to manage toasts:


const toast = useToast();
 
// Show a toast and get its information
const newToast = toast.show({
    title: "Title",
    message: "Message"
});
 
// Close a specific toast using its ID
toast.close(newToast.id);
 
// Close a toast by its index (0 is the oldest)
toast.closeByIndex(0);
 
// Get all current toasts
const allToasts = toast.getToasts();
 
// Close all toasts
toast.closeAll();
 
// Update global configuration
toast.updateConfig({
    defaultDirection: 'bottom-right',
    defaultOnlyShowOne: true
});

API

Toast Provider (Globally)

Configure the interface globally, but overrides are allowed to be overridden by the instance configuration.

import { ToastProvider } from 'funda-ui/Toast';
PropertyTypeDefaultDescriptionRequired
defaultWrapperClassNamestring-The class name of the toast wrapper.-
defaultOnlyShowOnebooleanfalseOnly ever going to show one toast at a time.-
defaultCascadingbooleanfalseWhether to use cascading styles.-
defaultReverseDisplaybooleanfalseAllow data to be reversed.-
defaultDirectionbottom-left | bottom-center | bottom-right | top-left | top-center | top-right | vertical-centerbottom-centerThe direction of the toast-

Hook

import { useToast } from 'funda-ui/Toast';

The useToast hook returns an object with the following methods:

MethodParametersReturn TypeDescription
showToastOptionsToastItemShows a new toast and returns the toast object including its ID
closeid: stringvoidCloses a specific toast by its ID
closeByIndexindex: numbervoidCloses a toast by its index (0 is the oldest)
closeAll-voidCloses all currently displayed toasts
getToasts-ToastItem[]Returns an array of all currently active toasts
updateConfig-voidUpdate the global default configuration

Toast Options

The ToastOptions object accepts the following properties:

PropertyTypeDefaultDescriptionRequired
actionIdstring | number | null | undefined-The identifier of useToast().show(), which can be used to determine whether different useToast().show()-
titlestring | ReactNode | boolean-Specifies an alternate and title for the toast-
notestring | ReactNode | boolean-A light-colored comment next to the title, which can be information such as time.-
messagestring | ReactNode-Specifies the content, or HTML elements to the toast-
themeprimary | secondary | success | info | warning | danger | light | dark | undefinedundefinedSpecifies a theme to .toast. All these colors are available as a Sass map of Bootstrap.-
wrapperClassNamestring-The class name of the toast wrapper.-
onlyShowOnebooleanfalseOnly ever going to show one toast at a time.-
lockbooleanfalseYou can not close pop-win when it is enabled.-
cascadingbooleanfalseWhether to use cascading styles.-
schemeBodystring-Self-defined class name for body, such as: align-items-center text-white bg-primary border-0-
schemeHeaderstring-Self-defined class name for header, such as: text-white bg-dark-
closeBtnColorstring-Set the color of the close button.-
closeDisabledbooleanfalseDisable the close button.-
reverseDisplaybooleanfalseAllow data to be reversed.-
directionbottom-left | bottom-center | bottom-right | top-left | top-center | top-right | vertical-centerbottom-centerThe direction of the toast-
autoCloseTimeboolean | numberfalseSet an automatic closing time, multiple items will be accumulated in order. Amount of time measured in milliseconds. If false or without this attribute, Auto-Close will be disabled.-
onClosefunction-Call a function when the modal is opened. It returns three callback values.
  1. The first is the current element (HTMLDivElement)
  2. The second is the current index of removed item (Number)
  3. The third is the all displayed elements (HTMLDivElement[])
-

ToastItem

The object returned by show() and getToasts() includes:

PropertyTypeDescription
idstringUnique identifier for the toast
...ToastOptionsToastOptionsAll properties from ToastOptions

Legacy Component API

While we recommend using the useToast hook, the component API is still supported for backwards compatibility. See the legacy documentation for details on using the <Toast /> component directly.