SweetAlert

repository·master·Indexed 12 days ago

https://github.com/t4t5/sweetalert

A beautiful, user-friendly replacement for JavaScript's standard alert, confirm, and prompt functions. Version 2.1.2 provides highly customizable modal dialogs with support for Promises, async/await, and custom DOM content. It includes built-in icons (warning, error, success, info) and an optional @sweetalert/with-react package for direct JSX integration.

Tokens
7.2K
Snippets
31
Records
35
Agent score
97%

What's inside SweetAlert

  1. Handle user interaction with SweetAlert Promises

    master

    SweetAlert returns a Promise that tracks user interaction.

    • If the user clicks the confirm button, the promise resolves to true (or a specific value if configured).
    • If the alert is dismissed (e.g., clicking outside the modal), the promise resolves to null.

    Dangerous Actions

    To warn users before dangerous actions, use these options:

    • icon: "warning": Shows a warning icon.
    • buttons: true: Adds a cancel button.
    • dangerMode: true: Sets focus to the cancel button and colors the confirm button red.
    swal({
      title: "Are you sure?",
      text: "Once deleted, you will not be able to recover this imaginary file!",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    }).then((willDelete) => {
      if (willDelete) {
        swal("Poof! Your imaginary file has been deleted!", { icon: "success" });
      } else {
        swal("Your imaginary file is safe!");
      }
    });
  2. Show a basic alert

    master

    Call the swal function after the DOM has loaded. You can pass arguments in several ways:

    1. Single string: Shows a simple alert with the string as text.
    2. Two strings: The first is the title, the second is the text.
    3. Three arguments: The third argument is an icon (one of: "warning", "error", "success", or "info").
    4. Options object: Pass a single object to customize multiple properties like title, text, icon, and button.
    // Simple alert
    swal("Hello world!");
    
    // Title and text
    swal("Here's the title!", "...and here's the text!");
    
    // Title, text, and icon
    swal("Good job!", "You clicked the button!", "success");
    
    // Using an options object
    swal({
      title: "Good job!",
      text: "You clicked the button!",
      icon: "success",
      button: "Aww yiss!",
    });
  3. Upgrade from SweetAlert 1.X to 2.X

    master

    SweetAlert 2.0 introduced breaking changes to improve flexibility. Key changes include:

    • Promises over Callbacks: Callback functions are deprecated; use Promises instead.
    • Bundled Styles: You no longer need to import an external CSS file; styles are bundled within the .js file.
    • String Parameter Behavior: Passing a single string (e.g., swal("Hello")) now sets the modal's text instead of its title.
    • Icon Configuration: The type and imageUrl options are replaced by a single icon option (though the shorthand swal("Hi", "Hello", "warning") remains compatible).
    • Naming Changes:
      • customClass $\rightarrow$ className
      • allowEscapeKey $\rightarrow$ closeOnEsc
      • allowClickOutside $\rightarrow$ closeOnClickOutside
  4. Integrate SweetAlert with React

    master

    To use JSX directly within SweetAlert, install the @sweetalert/with-react package alongside sweetalert.

    Instead of importing from sweetalert, import from @sweetalert/with-react. This allows you to pass JSX directly to the swal() function or the content option, replacing the need for manual DOM node manipulation.

    import React from 'react'
    import swal from '@sweetalert/with-react'
    
    swal(
      <div>
        <h1>Hello world!</h1>
        <p>This is now rendered with JSX!</p>
      </div>
    )
  5. Use DOM nodes as modal content

    master

    The content option allows you to render custom UI inside the modal. While content: "input" is a built-in shortcut for a text input, you can pass any DOM node.

    If you are using a library like React to build complex UIs, you must:

    1. Render your component into a DOM node (e.g., using ReactDOM.render).
    2. Pass that node to the content option.
    3. Use swal.setActionValue(value) within your custom component to update the value that the SweetAlert promise will resolve to when the confirm button is clicked.
    // Example: Using a custom DOM node from React
    // (Assuming 'el' is a DOM node extracted from a React component)
    swal({
      text: "Write something here:",
      content: el,
      buttons: {
        confirm: {
          value: "", // Initialize the value
        },
      },
    }).then((value) => {
      swal(`You typed: ${value}`);
    });
    
    // Inside your custom component's change handler:
    // swal.setActionValue(newValue);
  6. Use SweetAlert with React

    master

    To use SweetAlert with React components, install the @sweetalert/with-react package. This allows you to pass JSX directly into the swal function.

    import React from 'react'
    import swal from '@sweetalert/with-react'
    
    swal(
      <div>
        <h1>Hello world!</h1>
        <p>
          This is now rendered with JSX!
        </p>
      </div>
    )
  7. Install SweetAlert via NPM, Yarn, or CDN

    master

    You can install SweetAlert using a package manager or include it directly via a CDN.

    Use NPM or Yarn along with a bundler like Webpack or Browserify.

    npm install sweetalert --save

    Then import it into your application:

    import swal from 'sweetalert';

    CDN

    You can use the global swal variable by including the script from unpkg or jsDelivr.

  8. Understand SweetAlert argument patterns

    master

    SweetAlert supports two primary ways to trigger a modal: passing a single configuration object or passing multiple positional arguments. The getOpts function internally transforms these different patterns into a unified SwalOptions object.

    Positional Argument Patterns

    Depending on the number and type of arguments provided, the library interprets them as follows:

    1. Single String: swal("Message") $\rightarrow$ sets text.
    2. Two Strings: swal("Title", "Message") $\rightarrow$ sets title and text.
    3. Two Strings + Icon: swal("Title", "Message", "warning") $\rightarrow$ sets title, text, and icon.
    4. DOM Node: swal(domNode) $\rightarrow$ sets content to the provided node.
    5. Configuration Object: swal({ title: "...", icon: "..." }) $\rightarrow$ uses the object properties directly.

    Constraints

    • Buttons: You cannot provide both the button (single button) and buttons (button list) options simultaneously. If both are present, the library will throw an error: Cannot set both 'button' and 'buttons' options!.
    • Trailing Arguments: When using positional arguments (like strings or DOM nodes), you cannot provide extra arguments after the configuration is complete. For example, providing a fourth argument after an icon will trigger an error.
    // Positional arguments pattern
    swal("Wait!", "Are you sure?", "warning");
    
    // Configuration object pattern
    swal({
      title: "Wait!",
      text: "Are you sure?",
      icon: "warning"
    });
  9. Define button lists using different formats

    master

    SweetAlert supports several ways to define the buttons configuration, ranging from simple strings to complex objects.

    1. String (Single Button)

    Passing a string sets the text of the confirm button and makes it visible. The cancel button remains hidden by default.

    buttons: 'Accept'

    2. Array (Two Buttons)

    Passing an array of up to two strings maps them to the cancel and confirm buttons respectively.

    • ['No', 'Ok!'] $\rightarrow$ Cancel button text is 'No', Confirm button text is 'Ok!'.
    • ['Accept'] $\rightarrow$ Only the confirm button is updated; cancel remains hidden.
    • Note: Arrays with more than 2 elements will throw an error. For more than 2 buttons, use an object.
    buttons: ['No', 'Ok!']

    3. Object (Custom Buttons)

    Passing an object allows for full control over multiple buttons using their keys (confirm, cancel, or custom names).

    buttons: {
      confirm: { text: 'Yes', value: true, className: 'green' },
      cancel: { text: 'No', value: false },
      custom: { text: 'Help', value: 'help_requested' }
    }

    4. Boolean

    • true: Sets up a standard two-button layout (Cancel/Confirm) where both are visible.
    • false: Sets up a standard two-button layout where both are hidden.
    // Using an object for granular control
    const options = {
      buttons: {
        confirm: { text: 'OK', value: true },
        cancel: { text: 'Cancel', value: false }
      }
    };