React-Toastify

repository·main·Indexed 12 days ago

https://github.com/fkhadra/react-toastify

A highly customizable notification library for React applications (version 11.1.0) that allows developers to easily trigger and manage toast messages. Features include support for custom animations, swipe-to-close, RTL, dark mode, and the ability to render React components directly inside toasts. It includes a ToastContainer for hosting notifications and a programmatic toast() function for triggering them, as well as a useNotificationCenter hook for managing notification state, read/unread status, and filtering.

Tokens
7.2K
Snippets
29
Records
38
Agent score
96%

What's inside React-Toastify

  1. Overview of React-Toastify features

    main

    React-Toastify provides a wide range of features for managing notifications:

    • Customization: Easy to style and supports custom animations (e.g., with animate.css).
    • Interaction: Supports swipe-to-close with configurable directions.
    • Components: You can render React components directly inside a toast.
    • Hooks: Provides onOpen and onClose hooks that can access props passed to the internal React component.
    • Control: Ability to remove toasts programmatically, update existing toasts, and pause the timer programmatically.
    • Behavior: Supports RTL (Right-to-Left), dark mode, limiting the number of simultaneous toasts, and pausing toasts when the window loses focus.
    • Visuals: Includes a progress bar that can be controlled manually (similar to nprogress) and supports stacked notifications.
  2. Quickstart: Display a basic toast notification

    main

    To use react-toastify, you need to import ToastContainer and toast from the package. The ToastContainer must be rendered in your application (usually at the top level) to host the notifications, while toast() is called to trigger them.

    import React from 'react';
    import { ToastContainer, toast } from 'react-toastify';
    
    function App() {
      const notify = () => toast("Wow so easy!");
    
      return (
        <div>
          <button onClick={notify}>Notify!</button>
          <ToastContainer />
        </div>
      );
    }
  3. Customize ToastClassName

    main

    ToastClassName allows for dynamic styling of toasts or progress bars. It can be a raw string or a function that receives a context object to build a string.

    The context object contains:

    • type: The TypeOptions of the toast.
    • defaultClassName: The default classname.
    • position: The ToastPosition of the toast.
    • rtl: Boolean indicating right-to-left direction.
    const myClassName = (context) => {
      return context.type === 'error' ? 'my-error-class' : 'my-default-class';
    };
  4. Customize ToastContent

    main

    ToastContent allows you to pass custom content to a toast. It can be a React.ReactNode or a function that receives ToastContentProps.

    If using the function pattern, you can access:

    • closeToast: A function to close the toast.
    • toastProps: The ToastProps associated with the toast.
    • isPaused: Boolean indicating if the toast is currently paused.
    • data: The custom data passed to the toast via ToastOptions.data.
    <ToastContent>={({ closeToast, data }) => (
      <div>
        Custom Content: {data.someValue}
        <button onClick={closeToast}>Close Me</button>
      </div>
    )}</ToastContent>
  5. Configure ToastContainerProps

    main

    ToastContainerProps defines the configuration for the ToastContainer component, which manages the display of all toasts. Options include:

    • limit: Limit the number of toasts displayed at the same time.
    • newestOnTop: Whether or not to display the newest toast on top. (Default: false)
    • stacked: Will stack the toast with the newest on the top.
    • hotKeys: A function to define a keyboard shortcut to focus the first notification (e.g., Alt+t).
    • nonce: CSP nonce applied to the injected <style> tag.
    • className: An optional CSS class for the container.
    • style: An optional inline style for the container.
    • toastClassName: An optional CSS class for the toasts within the container.
  6. Configure Common Toast Options

    main

    CommonOptions are properties available to both individual toasts and the ToastContainer. Key options include:

    • autoClose: Set the delay in ms to close automatically. Use false to prevent auto-closing. (Default: 5000)
    • pauseOnHover: Pause the timer when the mouse hovers over the toast. (Default: true)
    • pauseOnFocusLoss: Pause the toast when the window loses focus. (Default: true)
    • closeOnClick: Remove the toast when clicked. (Default: false)
    • draggable: Allow toast to be draggable. Values: true, 'mouse', or 'touch'. (Default: 'touch')
    • theme: Set the theme ('light', 'dark', or 'colored'). (Default: 'light')
    • position: Set the default position. (Default: 'top-right')
    • hideProgressBar: Hide or show the progress bar. (Default: false)
    • closeButton: Pass a custom close button or set to false to remove it.
  7. Configure ToastOptions for individual toasts

    main

    ToastOptions extends CommonOptions and provides properties specific to a single toast instance:

    • type: Set the toast type ('info', 'success', 'warning', 'error', or 'default').
    • className: An optional CSS class or a function that returns a string to build a classname.
    • style: An optional inline style object.
    • onOpen: Callback function called when the toast is mounted.
    • onClose: Callback function called when the toast is unmounted. Receives a reason (boolean or string).
    • toastId: Set a custom toastId.
    • data: Pass custom data to the toast, useful when using custom components.
    • isLoading: Set to true to show a loading state.
  8. Configure sorting and filtering in useNotificationCenter

    main

    You can customize how notifications are displayed by providing sort and filter functions in the hook's parameters.

    Custom Sorting

    To change the order (e.g., showing oldest notifications first), provide a SortFn:

    useNotificationCenter({
      sort: (l, r) => l.createdAt - r.createdAt
    });

    Custom Filtering

    To only show specific notifications (e.g., hiding those marked as hidden in their data), provide a FilterFn:

    useNotificationCenter({
      filter: item => item.data.hidden === false
    });
    // old notifications first
    useNotificationCenter({
      sort: ((l, r) => l.createdAt - r.createdAt)
    })
    
    // keep only the toasts when hidden is set to false
    useNotificationCenter({
      filter: item => item.data.hidden === false
    })
  9. Handle promises with toast.promise

    main

    The toast.promise method allows you to supply a promise (or a function returning a promise) and automatically update the notification based on its state (pending, success, or error).

    toast.promise returns the original promise, allowing you to chain it.

    Simple Usage

    Pass strings for the pending, success, and error states.

    Advanced Usage

    Pass an object to pending, success, or error to customize the rendering (e.g., using a custom component or changing icons) and to access the resolved/rejected data.

    // Simple example
    tost.promise(MyPromise, {
      pending: 'Promise is pending',
      success: 'Promise resolved 👌',
      error: 'Promise rejected 🤯'
    });
    
    // Advanced usage with data access
    tost.promise<{name: string}, {message: string}, undefined>(
      resolveWithSomeData,
      {
        pending: {
          render: () => "I'm loading",
          icon: false,
        },
        success: {
          render: ({data}) => `Hello ${data.name}`,
          icon: "🟢",
        },
        error: {
          render({data}){
            return <MyErrorComponent message={data.message} />
          }
        }
      }
    )
  10. Add the ToastContainer to your application

    main

    To render notifications on the screen, you must include the ToastContainer component (exported as StyledToastContainer) in your application's component tree. This component acts as the mounting point for all toasts triggered via the toast API.

    import { ToastContainer } from 'react-toastify';
    
    function App() {
      return (
        <div>
          <ToastContainer />
          {/* Your application content */}
        </div>
      );
    }