solid-toast

repository·main·Indexed 21 days ago

https://github.com/ardeora/solid-toast

A lightweight, accessible, and customizable toast notification library for SolidJS version 0.5.0. It supports SSR, Promise-based notifications via toast.promise(), and flexible custom JSX rendering. The library provides a Toaster component for global configuration and a toast() API for triggering various notification types including success, error, loading, blank, and custom toasts.

Tokens
3.7K
Snippets
19
Records
20
Agent score
72%

What's inside solid-toast

  1. Get started with solid-toast

    main

    To use solid-toast, you must first add the <Toaster /> component to your component tree. This component acts as the container that renders all toasts. Once the <Toaster /> is mounted, you can trigger notifications from anywhere in your application using the toast() function.

    import toast, { Toaster } from 'solid-toast';
    
    const notify = () => toast('Here is your toast.');
    
    const App = () => {
      return (
        <div>
          <button onClick={notify}>Make me a toast</button>
          <Toaster />
        </div>
      );
    };
  2. Install solid-toast

    main

    You can install solid-toast using either yarn or npm to add toast notifications to your SolidJS project.

    yarn add solid-toast
    # or
    npm install solid-toast
  3. Use dynamic messages with ValueOrFunction

    main

    The message property (and the Message type) supports both static values and dynamic functions. This allows you to render content based on the current state of the toast itself.

    • Static: A Renderable (JSX element, string, or null).
    • Dynamic: A function with the signature (arg: Toast) => Renderable. The argument passed to the function is the Toast object itself, allowing you to access properties like id or type during rendering.
    // Using a function to create a dynamic message
    toast((toast) => `Toast ID: ${toast.id}`);
  4. Use the toast() function

    main

    The toast() function is the primary way to create notifications. It can be called with a message string or a custom JSX element. You can pass an optional ToastOptions object as the second argument to override default settings.

    toast('This is a simple toast!', {
      duration: 5000,
      position: 'top-right',
      unmountDelay: 500,
      style: {
        'background-color': '#f00',
      },
      className: 'my-custom-class',
      icon: '🍩',
      iconTheme: {
        primary: '#fff',
        secondary: '#000',
      },
      aria: {
        role: 'status',
        'aria-live': 'polite',
      },
    });
  5. Dismiss and remove toasts

    main

    You can manage active toasts using the following utility methods:

    • toast.dismiss(id?): Dismisses a single toast by its id. If no id is provided, it dismisses all toasts. This triggers the exit animation (defaulting to a 500ms delay unless unmountDelay is configured).
    • toast.remove(id?): Removes toasts instantly without triggering any exit animations.

    Note: Each toast() call returns a unique id that you can use for these operations.

    // Dismiss a specific toast
    const toastId = toast.loading('Loading...');
    toast.dismiss(toastId);
    
    // Dismiss all toasts with animation
    toast.dismiss();
    
    // Remove all toasts instantly
    toast.remove();
  6. Configure the Toaster component

    main

    The <Toaster /> component accepts several props to define the global behavior and appearance of all toasts in your application.

    <Toaster
      position="top-center"
      gutter={8}
      containerClassName=""
      containerStyle={{}}
      toastOptions={{
        // Default options for all toasts
        className: '',
        duration: 5000,
        style: {
          background: '#363636',
          color: '#fff',
        },
      }}
    />
  7. Update an existing toast

    main

    You can transform an existing toast (e.g., changing a loading toast into a success toast) by passing the original toast's id in the options object of a new toast call.

    const toastId = toast.loading('Loading...');
    
    // ... later ...
    
    toast.success('This worked', {
      id: toastId,
    });
  8. Create different types of toasts

    main

    solid-toast provides several specialized methods for common notification patterns:

    • Blank: toast('Message') - A simple toast without a default icon.
    • Success: toast.success('Message') - Displays an animated checkmark.
    • Error: toast.error('Message') - Displays an animated error icon.
    • Loading: toast.loading('Message') - Displays a loading indicator.
    • Promise: toast.promise(promise, options) - Automatically manages a toast lifecycle based on a Promise's state (loading, success, or error).
    • Custom: toast.custom(() => JSX) - Allows you to render entirely custom JSX elements.
    // Promise example
    const myPromise = fetchData();
    
    toast.promise(myPromise, {
      loading: 'Loading',
      success: <b>Got the data</b>,
      error: 'An error occurred 😔',
    });
    
    // Custom toast with lifecycle access
    toast.custom(
      (t) => (
        <div>
          <h1>Custom Toast</h1>
          <p>{t.visible ? 'Showing' : 'I will close in 1 second'}</p>
          <button onClick={() => toast.dismiss(t.id)}>Close Toast</button>
        </div>
      ),
      {
        unmountDelay: 1000,
      }
    );
  9. Use the toast() function to trigger notifications

    main

    The toast object is the primary API for triggering notifications. You can trigger a generic 'blank' toast using toast(message, options) or use specialized methods for specific toast types.

    Available methods:

    • toast(message, options): Creates a default 'blank' toast.
    • toast.success(message, options): Creates a success toast.
    • toast.error(message, options): Creates an error toast.
    • toast.loading(message, options): Creates a loading toast.
    • toast.custom(message, options): Creates a custom toast.

    Each method returns the toastId (a string) which can be used to dismiss or remove the toast later.

    import { toast } from 'solid-toast';
    
    // Basic usage
    toast.success('Operation successful!');
    
    // With custom options
    toast.error('Something went wrong', { duration: 5000 });
    
    // Capturing ID for manual dismissal
    const id = toast.loading('Uploading...');
    // ... later
    toast.dismiss(id);
  10. Dismiss or remove toasts by ID

    main

    You can manually control the visibility or existence of a toast using the toast.dismiss and toast.remove methods. Both accept an optional toastId string.

    • toast.dismiss(toastId?): Hides the toast from view (triggers a dismissal action).
    • toast.remove(toastId?): Completely removes the toast from the internal store.

    If no toastId is provided, these methods typically act on the most recent toast or follow the internal dispatch logic for clearing toasts.

    const id = toast.success('Saved!');
    
    // Hide the toast
    toast.dismiss(id);
    
    // Completely remove the toast from the store
    toast.remove(id);
  11. Configure toast appearance and behavior with ToastOptions

    main

    When calling the toast() function, you can pass an optional ToastOptions object to customize individual toast instances.

    Available options include:

    • id: A unique identifier for the toast.
    • icon: A Renderable (JSX element, string, or null) to display as an icon.
    • duration: The time in milliseconds before the toast automatically dismisses.
    • ariaProps: Accessibility properties including role ('status' | 'alert') and 'aria-live' ('assertive' | 'off' | 'polite').
    • className: A string for custom CSS classes.
    • style: A JSX.CSSProperties object for inline styling.
    • position: The screen position using ToastPosition (e.g., 'top-right', 'bottom-center').
    • unmountDelay: Delay in milliseconds before the toast is unmounted from the DOM.
    • iconTheme: An IconTheme object containing primary and secondary color strings.
    // Example of ToastOptions usage
    toast('Operation successful', {
      type: 'success',
      duration: 3000,
      position: 'top-right',
      iconTheme: { primary: '#4caf50' }
    });
  12. Handle promises with toast.promise()

    main

    The toast.promise method allows you to link a Promise's lifecycle (loading, success, and error states) to a toast notification. It automatically manages the transition between these states.

    Arguments:

    • promise: The Promise to monitor.
    • msgs: An object containing the content for each state:
      • loading: The content to show while the promise is pending.
      • success: The content to show when the promise resolves. This can be a static value or a function that receives the resolved value.
      • error: The content to show when the promise rejects. This can be a static value or a function that receives the error.
    • opts: Optional DefaultToastOptions to apply to the toast.

    Returns the original promise.

    const myPromise = fetchData();
    
    toast.promise(myPromise, {
      loading: 'Fetching data...',
      success: (data) => `Data loaded: ${data.name}`,
      error: (err) => `Error: ${err.message}`,
    });