SweetAlert2 Recipe Gallery

website·Indexed 29 days ago

https://sweetalert2.github.io/

A collection of comprehensive examples and implementation guides for SweetAlert2. Includes recipes for React, Laravel, and React Router integrations, as well as custom implementations for login forms, PDF viewers, image cropping with Cropper.js, colored toasts, and internationalization (i18n).

Tokens
14.2K
Snippets
65
Records
85
Agent score
75%

What's inside SweetAlert2

  1. Trigger SweetAlert2 popups declaratively via click handlers

    You can bind HTML buttons to trigger popups using Swal.bindClickHandler(). Use the data-swal-template attribute to specify which template to fire. You can also bind specific mixins to custom data attributes.
    <button data-swal-template="#my-template">Trigger modal</button>
    <button data-swal-toast-template="#my-template">Trigger toast</button>
    
    <script>
      // Bind default click handlers
      Swal.bindClickHandler();
    
      // Bind a specific mixin to a custom attribute
      Swal.mixin({ toast: true }).bindClickHandler("data-swal-toast-template");
    </script>
  2. Render React Router components inside SweetAlert2 using createPortal

    To use React state and React Router components (such as <Link />) inside a SweetAlert2 modal, use createPortal from react-dom. This allows the modal content to remain within the React component tree and share the same context as the rest of the application.

    createPortal requires two arguments: the React component to render and the target DOM element. SweetAlert2 provides helper methods to retrieve the correct target elements:

    • Swal.getTitle(): Target for the modal title.
    • Swal.getHtmlContainer(): Target for the modal main content area.
    • Swal.getFooter(): Target for the modal footer.
    import { createPortal } from 'react-dom'
    import { Link } from 'react-router-dom'
    import Swal from 'sweetalert2'
    
    // Example: Rendering a React Router Link inside the SweetAlert2 content area
    createPortal(
      <Link to="/about" onClick={() => Swal.close()}>
        Go to About
      </Link>,
      Swal.getHtmlContainer()!
    )
    
  3. Implement a SweetAlert2 modal with React Router navigation

    This example demonstrates how to trigger a SweetAlert2 modal and use a state variable to conditionally render a React Router <Link> inside the modal using createPortal. The didOpen and didClose lifecycle hooks of Swal.fire are used to manage the visibility of the portal content.
    import ReactDOM from 'react-dom/client'
    import { createPortal } from 'react-dom'
    import { useState } from 'react'
    import { BrowserRouter, Link, Route, Routes } from 'react-router-dom'
    import Swal from 'sweetalert2'
    
    const Home = () => {
      const [swalShown, setSwalShown] = useState(false)
    
      const showSwal = () => {
        Swal.fire({
          didOpen: () => setSwalShown(true),
          didClose: () => setSwalShown(false),
        })
      }
    
      return (
        <>
          <h1>Home</h1>
          <button onClick={showSwal}>Show SweetAlert2 modal</button>
    
          {/* Use createPortal to maintain React context/state inside the Swal modal */}
          {swalShown &&
            createPortal(
              <Link to="/about" onClick={() => Swal.close()}>
                Go to About
              </Link>,
              Swal.getHtmlContainer()!
            )}
        </>
      )
    }
    
    ReactDOM.createRoot(document.querySelector('.app-root')!).render(
      <BrowserRouter>
        <Link to="/">Home</Link> {' | '} 
        <Link to="/about">About</Link>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<div>About Page</div>} />
        </Routes>
      </BrowserRouter>
    )
    
  4. Define popups using declarative HTML templates

    SweetAlert2 supports defining popups via the HTML <template> tag, which is useful for Server-Side Rendering (SSR). You can trigger these templates by passing the template ID to Swal.fire({ template: '#id' }).

    Security Warning: The value attribute of <swal-function-param> is evaluated using new Function(), which behaves like eval(). Only use this with trusted content.

    <template id="my-template">
      <swal-title>Save changes to "Untitled 1" before closing?</swal-title>
      <swal-icon type="warning" color="red"></swal-icon>
      <swal-button type="confirm">Save As</swal-button>
      <swal-button type="cancel">Cancel</swal-button>
      <swal-button type="deny">Close without Saving</swal-button>
      <swal-param name="allowEscapeKey" value="false" />
      <swal-param name="customClass" value='{ "popup": "my-popup" }' />
      <swal-function-param name="didOpen" value="popup => console.log(popup)" />
    </template>
    
    <script>
      Swal.fire({ template: "#my-template" });
    </script>
  5. Install and configure SweetAlert2 in Laravel

    To integrate SweetAlert2 into a Laravel application, install the official sweetalert2/laravel package via Composer and include the provided Blade template in your main layout file (typically resources/views/layouts/app.blade.php).
    composer require sweetalert2/laravel

    <!-- In resources/views/layouts/app.blade.php --> @include('sweetalert2::index')

  6. Reuse SweetAlert2 configurations using mixins

    Use Swal.mixin({...options}) to create a reusable configuration. This is particularly useful for creating consistent toast notifications or themed alerts without repeating the same options in every Swal.fire() call.
    Swal.mixin({
      toast: true,
      position: "top-end",
      showConfirmButton: false,
      timer: 3000,
      timerProgressBar: true,
      didOpen: (toast) => {
        toast.onmouseenter = Swal.stopTimer;
        toast.onmouseleave = Swal.resumeTimer;
      }
    }).fire({
      icon: "success",
      title: "Signed in successfully"
    });
  7. Integrate react-day-picker with SweetAlert2 using React Portals

    To use a React component like react-day-picker inside a SweetAlert2 modal while maintaining shared state, use createPortal from react-dom. This allows you to render the React component into the DOM elements managed by SweetAlert2.

    Target elements for the portal can be retrieved using:

    • Swal.getTitle(): For the title area.
    • Swal.getHtmlContainer(): For the main content area.
    • Swal.getFooter(): For the footer area.
    import ReactDOM from 'react-dom/client'
    import { createPortal } from 'react-dom'
    import { useState } from 'react'
    import Swal from 'sweetalert2'
    import { DayPicker } from 'react-day-picker'
    import 'react-day-picker/dist/style.css'
    import type { DateRange } from 'react-day-picker'
    
    function App() {
      const [swalShown, setSwalShown] = useState(false)
      const [range, setRange] = useState<DateRange | undefined>()
    
      function showSwalWithReactDayPicker() {
        Swal.fire({
          title: 'Select a range of dates',
          didOpen: () => setSwalShown(true),
          didClose: () => setSwalShown(false),
        })
      }
    
      return (
        <>
          <button onClick={showSwalWithReactDayPicker}>Show SweetAlert2</button>
    
          {/* Render the DayPicker into the SweetAlert2 HTML container when the modal is open */}
          {swalShown &&
            createPortal(
              <DayPicker 
                mode="range" 
                selected={range} 
                onSelect={setRange} 
                style={{ display: 'inline-block' }} 
              />,
              Swal.getHtmlContainer()!
            )
          }
        </>
      )
    }
  8. Import and use SweetAlert2 in JavaScript

    Import the Swal object to trigger modal alerts. You can import the bundled version or separate JS and SCSS files for custom styling.
    import Swal from 'sweetalert2'
    
    // Or via CommonJS
    const Swal = require('sweetalert2')
    
    // To customize styles, import separately:
    import Swal from 'sweetalert2/dist/sweetalert2.js'
    import 'sweetalert2/src/sweetalert2.scss'
    
    // Basic usage
    Swal.fire({
      title: 'Error!',
      text: 'Do you want to continue',
      icon: 'error',
      confirmButtonText: 'Cool'
    })
    
  9. Install SweetAlert2

    SweetAlert2 can be installed via npm or included via a CDN script tag.
    npm install sweetalert2
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  10. Use JSX/TSX content in SweetAlert2 modals with React

    To use React components or JSX/TSX as parameters (such as title, html, etc.) in Swal.fire, use the sweetalert2-react-content integration. This wrapper allows SweetAlert2 to render React elements instead of plain strings.
    import Swal from 'sweetalert2';
    import withReactContent from 'sweetalert2-react-content';
    
    // Wrap Swal to enable React content support
    const SwalWithReact = withReactContent(Swal);
    
    const showSwal = () => {
      SwalWithReact.fire({
        title: <i>Input something</i>,
        input: 'text',
        inputValue: 'Initial value',
        preConfirm: () => {
          // Access input value using Swal.getInput()
          const value = Swal.getInput()?.value;
          console.log(value);
        },
      });
    };
  11. Configure progress step parameters in SweetAlert2

    When using progress steps in a SweetAlert2 popup, you can control the current step and the visual spacing between steps using the following configuration keys:

    • currentProgressStep: Defines the currently active progress step.
    • progressStepsDistance: Defines the distance between progress steps. This accepts any valid CSS unit, such as px, em, rem, or %.
  12. Use native HTML5 date inputs in SweetAlert2

    For simple date selection without external plugins, SweetAlert2 supports native HTML5 input types directly within the Swal.fire() configuration using the input parameter.
    Swal.fire({
      input: 'date', // Options: 'date', 'datetime-local', 'time', 'week', 'month'
    });