React-Toastify

website·Indexed 30 days ago

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

A React library for adding toast notifications to applications. It features a ToastContainer for global configuration, support for custom animations, built-in icons, and accessibility via ARIA roles. The library includes advanced functionality such as toast.promise for handling asynchronous tasks, controlled progress bars, and the useNotificationCenter headless hook. It supports React 18 or above and provides migration guides for v8 and v10.

Tokens
17.2K
Snippets
108
Records
113
Agent score
75%

What's inside React-Toastify

  1. Update an existing toast using toast.update

    To update an active toast, use the toast.update method. You must provide the toastId of the toast you wish to modify. When updating, existing toast options and content are inherited unless explicitly overridden in the update object.
    import { toast } from 'react-toastify';
    
    function Example() {
      const toastId = React.useRef(null);
    
      // Create a toast and store its ID
      const notify = () => {
        toastId.current = toast("Hello", { autoClose: false });
      };
    
      // Update the toast using the stored ID
      const update = () => {
        toast.update(toastId.current, { type: "info", autoClose: 5000 });
      };
    
      return (
        <div>
          <button onClick={notify}>Notify</button>
          <button onClick={update}>Update</button>
        </div>
      );
    }
  2. Remove specific or all toast notifications programmatically

    Each time a toast is displayed via toast(), it returns a unique ID. This ID can be passed to toast.dismiss(id) to remove that specific notification. If toast.dismiss() is called without any arguments, all currently displayed toasts will be removed.
    import React from 'react';
    import { toast } from 'react-toastify';
    
    function Example() {
      const toastId = React.useRef(null);
    
      // Store the ID returned by toast()
      const notify = () => {
        toastId.current = toast("Lorem ipsum dolor");
      };
    
      // Dismiss a specific toast using its ID
      const dismiss = () => toast.dismiss(toastId.current);
    
      // Dismiss all active toasts
      const dismissAll = () => toast.dismiss();
    
      return (
        <div>
          <button onClick={notify}>Notify</button>
          <button onClick={dismiss}>Dismiss</button>
          <button onClick={dismissAll}>Dismiss All</button>
        </div>
      );
    }
  3. Define custom closure reasons using closeToast

    When using a custom notification component, you can use the closeToast function (provided via ToastContentProps) to pass a custom reason string or value to the onClose callback. This is useful for notifications with multiple call-to-action buttons where you need to distinguish which action triggered the closure.
    import { toast, ToastContentProps } from "react-toastify";
    
    function CustomNotification({ closeToast }: ToastContentProps) {
      return (
        <div>
          You received a new message
          <button onClick={() => closeToast("reply")}>Reply</button>
          <button onClick={() => closeToast("ignore")}>Ignore</button>
        </div>
      );
    }
    
    toast(CustomNotification, {
      onClose(reason) {
        switch (reason) {
          case "reply":
            console.log("User replied");
            break;
          case "ignore":
            console.log("User ignored");
            break;
          default:
            console.log("Closed by other means");
        }
      }
    });
  4. Create a custom CSS transition for react-toastify

    Use the cssTransition function to define custom CSS class names for the enter and exit animations of toast notifications. This allows you to integrate third-party animation libraries (like Animate.css) or your own custom CSS transitions.
    import { cssTransition } from 'react-toastify';
    
    const Zoom = cssTransition({
      enter: 'zoomIn',
      exit: 'zoomOut',
      appendPosition: false,
      collapse: true,
      collapseDuration: 300
    });
  5. Automatic CSS injection in react-toastify v11

    Starting with v11, the stylesheet is injected automatically. Developers no longer need to manually import the CSS file to get basic styling, although the CSS file remains exported by the library for those who still need it.
    import { ToastContainer, toast } from 'react-toastify';
    
    function App(){
      const notify = () => toast("Wow so easy !");
    
      return (
        <div>
          <button onClick={notify}>Notify !</button>
          <ToastContainer />
        </div>
      );
    }
  6. Create custom CSS transitions for toasts

    Starting from v7, react-toastify supports CSS animations out of the box. You can use custom CSS classes or libraries like animate.css by importing cssTransition and defining the classes to be used when a toast enters and exits the screen.
    import { cssTransition } from "react-toastify";
    
    const bounce = cssTransition({
      enter: "animate__animated animate__bounceIn",
      exit: "animate__animated animate__bounceOut"
    });
  7. Import and initialize useNotificationCenter

    The useNotificationCenter hook is a headless utility for building a notification center on top of react-toastify. It provides a stateful list of notifications and methods to manipulate them. You can pass a generic type to the hook to define the structure of the data property on each notification item.
    import { useNotificationCenter, NotificationCenterItem } from "react-toastify/addons/useNotificationCenter"
    
    interface Data {
      order: number
    }
    
    function App(){
      // Pass the Data interface to type the notification data
      const { notifications, sort } = useNotificationCenter<Data>()
    
      const sortAsc = () => {
        sort((l: NotificationCenterItem, r: NotificationCenterItem) => l.data.order - r.data.order)
      }
    
      return (
        <div>
          <button onClick={sortAsc}>Oldest to newest</button>
          <ul>
            {notifications.map(notification => (
              <li key={notification.id}>
                <span>{notification.id}</span>
              </li>
            ))}
          </ul>
        </div>
      )
    }
  8. Render a custom component in a toast

    You can render any valid ReactNode (string, number, or component) to customize the look and feel of notifications. When a component is provided, react-toastify injects four props into it: closeToast, data, isPaused, and toastProps.
    import { ToastContainer, toast } from "react-toastify";
    
    const Msg = ({ closeToast, toastProps }) => (
      <div>
        Lorem ipsum dolor {toastProps.position}
        <button>Retry</button>
        <button onClick={closeToast}>Close</button>
      </div>
    );
    
    function App() {
      const displayMsg = () => {
        toast(Msg);
        // Alternatively: toast(<Msg />)
      };
    
      return (
        <div>
          <button onClick={displayMsg}>Click me</button>
          <ToastContainer />
        </div>
      );
    }
  9. Migrate to react-toastify v10 breaking changes

    Key breaking changes in v10 include:

    • React Version: React 18 is now the minimum required version.
    • Multi-Container: The enableMultiContainer prop is removed. Simply assigning an id to the ToastContainer is sufficient.
    • Constants: toast.POSITION and toast.TYPE constants have been removed in favor of TypeScript types.
    • Default Props:
      • closeOnClick is now false by default (previously true).
      • draggable is now touch by default (previously true), meaning it only works on touch devices unless explicitly set to true.
    // To restore v9 default behavior for closeOnClick
    <ToastContainer closeOnClick />
    
    // To enable dragging on all devices (including desktop)
    <ToastContainer draggable />
    
    // Correct way to use multiple containers in v10
    <ToastContainer id="myContainer" />
  10. Change the toast ID during an update

    You can change the toastId of an existing toast by providing a new toastId in the toast.update options. Note that any subsequent updates to this toast must use the new ID.
    const myNewToastId = 'loremIpsum';
    
    // Update the toast and change its ID
    toast.update(toastId, {
      render: "New content",
      type: "info",
      autoClose: 5000,
      toastId: myNewToastId
    });
    
    // Subsequent updates must use the new ID
    toast.update(myNewToastId, {
      render: MyComponent,
      autoClose: 6000
    });
  11. Reset toast options to inherit from ToastContainer

    To stop overriding a specific toast option and instead inherit the default value defined in the ToastContainer, pass null to that option during the toast.update call. This is useful for restoring elements like the closeButton that were previously disabled.
    const notify = () => {
      toastId.current = toast("Hello", {
        autoClose: false,
        closeButton: false // Explicitly remove close button
      });
    };
    
    const update = () => {
      toast.update(toastId.current, {
        type: "info",
        autoClose: 5000,
        closeButton: null // Reset to inherit closeButton from ToastContainer
      });
    };
  12. Implement a controlled progress bar for file uploads

    To create a toast that reflects a real-time progress percentage (e.g., during a file upload), use toast() to initialize the toast and toast.update() to modify the progress property. Store the toast ID in a reference (like React.useRef) to ensure you are updating the correct toast instance. Once the process is complete, call toast.done() to fill the progress bar and trigger the closing transition.
    import axios from 'axios';
    import { toast } from 'react-toastify';
    
    function Example() {
      // Keep a reference of the toastId to update the same toast
      const toastId = React.useRef(null);
    
      function handleUpload() {
        axios.request({
          method: "post", 
          url: "/foobar", 
          data: myData, 
          onUploadProgress: p => {
            const progress = p.loaded / p.total;
    
            // Initialize toast if it doesn't exist, otherwise update it
            if (toastId.current === null) {
              toastId.current = toast('Upload in Progress', { progress });
            } else {
              toast.update(toastId.current, { progress });
            }
          }
        }).then(data => {
          // Mark the toast as completed to fill the bar and close it
          toast.done(toastId.current);
        });
      }
    
      return (
        <div>
          <button onClick={handleUpload}>Upload something</button>
        </div>
      );
    }