SweetAlert2 - Documentation

Getting Started

Installation

SweetAlert2 can be installed via npm, yarn, or a CDN. For npm or yarn, use the following command:

npm install sweetalert2
# or
yarn add sweetalert2

After installation, import SweetAlert2 into your project:

import Swal from 'sweetalert2'

For CDN usage, include the following script tag in your HTML <head>:

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Remember to replace @11 with the desired version number. You can find the latest version number on the SweetAlert2 website or npm package page.

Basic Usage

SweetAlert2’s core functionality revolves around a single function, Swal(), which accepts an options object to customize the alert. This object can contain parameters to control various aspects of the alert, such as title, text, icon, and buttons. The simplest usage is to directly call the Swal() function:

Swal.fire('Hello world!');

This will display a basic alert box with the text “Hello world!”. More advanced usage involves passing an options object:

Swal.fire({
  title: 'Are you sure?',
  text: 'You won\'t be able to revert this!',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, keep it'
}).then((result) => {
  if (result.isConfirmed) {
    // User clicked "Yes, delete it!"
  } else if (result.isDenied) {
    // User clicked "No, keep it"
  }
})

This example shows a more complex alert with a title, text, warning icon, confirmation and cancellation buttons, and a then function to handle the user’s response.

First Alert Example

Let’s create a simple alert that displays a success message. This will demonstrate the basic structure and usage:

// Using a CDN, ensure the script is included before this code.
// For npm/yarn, ensure the import statement is present.

Swal.fire({
  icon: 'success',
  title: 'Success!',
  text: 'Your action was completed successfully.'
});

This code will display a SweetAlert2 box with a green success icon, the title “Success!”, and the text “Your action was completed successfully.” This provides a clear visual indication to the user about the outcome of an operation. Remember to handle any potential errors or edge cases in a production environment for a robust user experience.

Parameters

SweetAlert2 offers a wide array of parameters to customize the appearance and behavior of your alerts. These parameters are passed as key-value pairs within the options object to the Swal.fire() function. Below is a description of each parameter.

title

Type: string The title of the alert. Displayed prominently at the top.

html

Type: string Allows you to add HTML content to the alert body. This provides flexibility to include formatted text, images, or other elements.

icon

Type: string Specifies the icon to display. Options include 'success', 'error', 'warning', 'info', 'question', and null (to hide the icon).

text

Type: string The main text content of the alert. Appears below the title.

Type: string Text to display in the footer of the alert.

backdrop

Type: boolean | string Controls the backdrop behind the alert. true (default) displays a backdrop; false hides it; a string can specify a custom backdrop color (e.g., 'rgba(0,0,0,0.4)').

timer

Type: number Specifies a timer in milliseconds to automatically close the alert.

timerProgressBar

Type: boolean Displays a progress bar at the bottom of the alert that reflects the timer countdown.

width

Type: string Sets the width of the alert box. Can be a pixel value (e.g., '300px') or a percentage (e.g., '50%').

padding

Type: string Sets the padding of the alert box. Similar to width, can use pixel values or percentages.

customClass

Type: object Allows adding custom CSS classes to various elements of the alert for granular styling. Example: { container: 'my-container', title: 'my-title' }.

showClass

Type: object Specifies CSS classes for the alert’s animation when shown. Useful for custom animation effects.

hideClass

Type: object Specifies CSS classes for the alert’s animation when hidden. Useful for custom animation effects.

position

Type: string Specifies the position of the alert on the screen. Options include 'top', 'top-end', 'top-start', 'center', 'center-end', 'center-start', 'bottom', 'bottom-end', 'bottom-start'.

allowOutsideClick

Type: boolean Determines if the alert can be closed by clicking outside of it.

allowEscapeKey

Type: boolean Determines if the alert can be closed by pressing the Escape key.

allowEnterKey

Type: boolean Determines if the alert can be closed by pressing the Enter key.

stopKeydownPropagation

Type: boolean Prevents default keydown event propagation.

showConfirmButton

Type: boolean Whether to show the confirm button.

showDenyButton

Type: boolean Whether to show the deny button.

showCancelButton

Type: boolean Whether to show the cancel button.

confirmButtonText

Type: string Text for the confirm button.

denyButtonText

Type: string Text for the deny button.

cancelButtonText

Type: string Text for the cancel button.

confirmButtonColor

Type: string Color for the confirm button.

denyButtonColor

Type: string Color for the deny button.

cancelButtonColor

Type: string Color for the cancel button.

buttonsStyling

Type: boolean Whether to apply default SweetAlert2 styling to the buttons.

grow

Type: string This is a special parameter for the input parameter, specifying animation style (“increment”, “decrement”, “fullscreen”).

input

Type: string Specifies the type of input field to display (e.g., 'text', 'email', 'password', 'number', 'select', 'radio', 'checkbox', 'textarea').

inputValue

Type: string Pre-fills the input field with a value.

inputPlaceholder

Type: string Sets the placeholder text for the input field.

inputAttributes

Type: object Allows adding custom attributes to the input field (e.g., { required: true, min: 0 }).

inputValidator

Type: function A function to validate the input value. Returns a string if invalid, or undefined if valid.

inputAutoTrim

Type: boolean Whether to automatically trim whitespace from the input value.

progressSteps

Type: array An array of strings to display as progress steps (only relevant with input type 'range').

currentProgressStep

Type: number Sets the currently active progress step.

focusConfirm

Type: boolean Whether to automatically focus the confirm button on alert open.

focusDeny

Type: boolean Whether to automatically focus the deny button on alert open.

focusCancel

Type: boolean Whether to automatically focus the cancel button on alert open.

returnInputValueOnDeny

Type: boolean Whether to return the input value when the deny button is clicked.

returnInputValueOnCancel

Type: boolean Whether to return the input value when the cancel button is clicked.

didOpen

Type: function A function to execute after the alert is fully opened.

didClose

Type: function A function to execute after the alert is fully closed.

willOpen

Type: function A function to execute before the alert is opened. Useful for pre-processing tasks or animations.

willClose

Type: function A function to execute before the alert is closed. Useful for pre-closing tasks or animations.

didRender

Type: function A function to execute after the alert is rendered.

willRender

Type: function A function to execute before the alert is rendered.

closeOnClickOutside

Type: boolean Alias for allowOutsideClick.

closeOnEsc

Type: boolean Alias for allowEscapeKey.

closeOnConfirm

Type: boolean Whether to automatically close the alert on confirm button click.

closeOnDeny

Type: boolean Whether to automatically close the alert on deny button click.

closeOnCancel

Type: boolean Whether to automatically close the alert on cancel button click.

Icons

SweetAlert2 provides built-in icons to enhance the visual feedback of your alerts. You can also customize the icons or their styling to match your application’s design.

Available Icons

SweetAlert2 offers several predefined icons that you can use by setting the icon parameter in the Swal.fire() options object. The available icons are:

You can simply specify the icon name as a string in your Swal.fire() call:

Swal.fire({
  icon: 'success',
  title: 'Success!',
  text: 'Operation completed successfully!'
});

Custom Icons

While SweetAlert2 provides a set of default icons, you can also use custom icons. This is achieved by using the iconHtml parameter. This parameter allows you to inject arbitrary HTML content into the icon area:

Swal.fire({
  icon: 'error', // still set for default styling, even with custom HTML
  iconHtml: '<i class="my-custom-icon fas fa-exclamation"></i>',
  title: 'Custom Icon!',
  text: 'This alert uses a custom icon!'
});

This example uses a Font Awesome icon, but you can use any HTML element you like, such as an <img> tag for an image icon. Remember that the size and positioning of your custom icon might require additional CSS adjustments.

Icon Styling

You can style the built-in icons using CSS. The icons are wrapped in classes that you can target. For example, to change the color of the success icon, you might use:

.swal2-icon.swal2-success {
  color: #007bff !important; /* Example: Change to blue */
}

Similarly, you can target other icon classes (e.g., swal2-icon.swal2-error, swal2-icon.swal2-warning, etc.) to adjust their appearance. Remember to use the !important flag to override SweetAlert2’s default styles, if needed. For custom icons, style the classes you defined in the iconHtml content. Consider creating specific CSS classes for your custom icons to maintain clean and organized styles.

Input Types

SweetAlert2 supports various input types, allowing you to create interactive alerts that gather user input. To use input fields, set the input parameter in the Swal.fire() options object to the desired type. The alert will then display an input field appropriate for that type. Remember to handle the user’s input using the .then() method’s result.value property.

text

Type: 'text' A standard single-line text input field. Suitable for short text entries.

Swal.fire({
  input: 'text',
  inputLabel: 'Enter your name:',
  inputPlaceholder: 'Your name'
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value); // Access the entered text
  }
});

email

Type: 'email' An input field specifically designed for email addresses. Includes basic validation (checking for the “@” symbol).

Swal.fire({
  input: 'email',
  inputLabel: 'Enter your email:',
  inputPlaceholder: 'Your email'
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

password

Type: 'password' An input field for passwords. The entered text is masked with dots.

Swal.fire({
  input: 'password',
  inputLabel: 'Enter your password:',
  inputPlaceholder: 'Your password'
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

number

Type: 'number' A numerical input field. Allows for numeric input only. You can enhance this by using the inputAttributes parameter to set min, max, and step attributes.

Swal.fire({
  input: 'number',
  inputLabel: 'Enter a number:',
  inputAttributes: {
    min: 0,
    max: 100,
    step: 1
  }
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

tel

Type: 'tel' A telephone number input field.

Swal.fire({
  input: 'tel',
  inputLabel: 'Enter your phone number:',
  inputPlaceholder: 'Your phone number'
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

select

Type: 'select' A dropdown select input. Requires the inputOptions parameter to define the options.

Swal.fire({
  input: 'select',
  inputLabel: 'Select an option:',
  inputOptions: {
    'option1': 'Option 1',
    'option2': 'Option 2',
    'option3': 'Option 3'
  }
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

radio

Type: 'radio' A set of radio buttons. Requires the inputOptions parameter to define the options.

Swal.fire({
  input: 'radio',
  inputLabel: 'Select an option:',
  inputOptions: {
    'option1': 'Option 1',
    'option2': 'Option 2',
    'option3': 'Option 3'
  }
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

checkbox

Type: 'checkbox' A single checkbox. The inputValue parameter determines the value returned when checked.

Swal.fire({
  input: 'checkbox',
  inputLabel: 'Agree to terms:',
  inputValue: 1, // Value returned when checked
  inputPlaceholder: 'Check this box to agree.'
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value); // 1 if checked, null if unchecked.
  }
});

textarea

Type: 'textarea' A multi-line text input field. Suitable for longer text entries.

Swal.fire({
  input: 'textarea',
  inputLabel: 'Enter your comment:',
  inputPlaceholder: 'Your comment'
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

file

Type: 'file' An input field to select files. You can access the selected files through result.value. This will be an array of File objects.

Swal.fire({
  input: 'file',
  inputLabel: 'Select a file:',
  inputAttributes: {
    accept: 'image/*' //Optional: Specify accepted file types
  }
}).then((result) => {
  if (result.isConfirmed) {
    console.log(result.value);
  }
});

Remember to handle potential errors and sanitize user input appropriately in a production environment. The inputValidator parameter is particularly useful for validating input.

Styling

SweetAlert2 offers several ways to customize its appearance, allowing you to seamlessly integrate it into your application’s design.

CSS Classes

SweetAlert2 utilizes a number of CSS classes to style its elements. These classes provide a structured way to target and modify specific parts of the alert. A comprehensive list isn’t possible here as the number is extensive but by inspecting the rendered HTML of a SweetAlert2 popup (using your browser’s developer tools), you can identify the relevant classes to modify.

For example, to change the background color of the alert container, you might find a class like swal2-container and style it using CSS:

.swal2-container {
  background-color: #f0f0f0; /* Example: Light gray background */
}

Remember that SweetAlert2’s CSS might use !important flags to enforce its styles. To override these, you might need to use !important in your own CSS as well, though this should be avoided if possible for better maintainability. It’s best practice to inspect the generated HTML and target the most specific class possible to minimize unintended side effects.

Custom Styles

You can add custom CSS to your project to style the SweetAlert2 elements according to your design. This approach provides greater flexibility than modifying existing classes directly. You can create entirely new classes and use the customClass parameter to apply them:

Swal.fire({
  customClass: {
    container: 'my-custom-container',
    title: 'my-custom-title'
  },
  title: 'My Custom Alert',
  text: 'This alert uses custom styles.'
});

Then, create CSS rules for .my-custom-container and .my-custom-title in your stylesheet:

.my-custom-container {
  background-color: #f5f5f5;
  border-radius: 10px;
}

.my-custom-title {
  color: #333;
  font-weight: bold;
}

Themes

SweetAlert2 doesn’t directly support pre-built themes in the way that some UI frameworks do. However, you can easily achieve themed appearances using the techniques described above, primarily using custom CSS classes and the customClass parameter. You can create separate CSS files or CSS class sets for different themes. For instance, you could create a “dark theme” with custom classes that adjust colors, fonts, and other aspects for a dark mode appearance, and then use the appropriate classes based on user preference or application settings. This allows for full customization and control over the look and feel of your SweetAlert2 instances.

Advanced Usage

This section covers more advanced techniques for using SweetAlert2, allowing you to integrate it into complex applications.

Dynamic Content

SweetAlert2 allows you to easily incorporate dynamic content into your alerts. This is particularly useful when the content of the alert depends on data fetched from a server or other asynchronous operations. You can update the alert’s content using the Swal.update() method after the alert has been displayed:

Swal.fire({
  title: 'Loading...',
  html: 'Fetching data...'
}).then((result) => {
    //some code
}).then(() => {
  fetch('your-api-endpoint')
    .then(response => response.json())
    .then(data => {
      Swal.update({
        title: 'Data Loaded!',
        html: `Here's your data: ${JSON.stringify(data, null, 2)}`
      });
    });
});

This example first shows a loading message. After the AJAX request completes, Swal.update() modifies the alert’s title and HTML content to display the fetched data.

AJAX Requests

SweetAlert2 itself doesn’t handle AJAX requests directly, but it integrates seamlessly with JavaScript’s fetch API or other AJAX libraries like jQuery’s $.ajax(). You perform the AJAX request separately and then use the result to update the alert’s content using Swal.update() or create a new alert to display the results. Error handling should be included to gracefully handle failed requests:

Swal.fire({
  title: 'Loading...'
}).then(() => {
  fetch('your-api-endpoint')
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then(data => Swal.fire({ title: 'Success!', text: JSON.stringify(data) }))
    .catch(error => Swal.fire({ icon: 'error', title: 'Oops...', text: error.message }));
});

This example shows a loading alert, then makes an AJAX call. On success, it displays a success alert, and on error, an error alert is shown.

Promises

SweetAlert2’s Swal.fire() method returns a Promise. This allows you to chain asynchronous operations using .then() and .catch(). The Promise resolves with an object containing information about the user’s interaction with the alert (e.g., whether they clicked “OK,” “Cancel,” etc.):

Swal.fire({
  title: 'Are you sure?',
  showCancelButton: true
}).then((result) => {
  if (result.isConfirmed) {
    // Perform action based on confirmation
    console.log('Confirmed!');
  } else if (result.dismiss === Swal.DismissReason.cancel) {
    // Perform action based on cancellation
    console.log('Cancelled!');
  }
});

Asynchronous Operations

SweetAlert2 works well with asynchronous operations. You can initiate long-running tasks (like file uploads or complex calculations) before or after displaying an alert, or within the .then() block of the Promise returned by Swal.fire(). Use loading indicators (e.g., with the timerProgressBar option) or Swal.update() to provide feedback during long operations.

Multiple Alerts

You can display multiple SweetAlert2 alerts sequentially or concurrently. Sequential alerts are simply chained using .then(). Concurrent alerts are independent and will run simultaneously. However, be mindful of user experience — too many alerts at once can be overwhelming.

Queueing Alerts

For displaying several alerts in a sequence, consider using Swal.queue(). This function takes an array of alert options, executing them one after another:

const alerts = [
  Swal.mixin({
    confirmButtonText: 'Next &rarr;',
    progressSteps: ['1', '2', '3']
  }).queue([
    {
      title: 'Step 1',
      text: 'Some text'
    },
    {
      title: 'Step 2',
      text: 'Some text'
    },
    {
      title: 'Step 3',
      text: 'Some text'
    }
  ])
];
Swal.queue(alerts);

This example uses Swal.mixin to create a reusable alert configuration, then queues three steps that will execute sequentially. The user must confirm each step to proceed to the next one. Swal.queue handles the execution flow, ensuring alerts are shown in the defined order. This is useful for multi-stage processes or workflows.

Accessibility

SweetAlert2 is designed with accessibility in mind, incorporating features to improve usability for users with disabilities.

ARIA Attributes

SweetAlert2 automatically applies relevant ARIA attributes to its elements to enhance screen reader compatibility and keyboard navigation. These attributes provide semantic information about the alert’s purpose and interactive elements. While you generally don’t need to manually manage these attributes, understanding their role is crucial for ensuring your alerts are accessible. Key ARIA attributes used include:

These attributes allow assistive technologies (like screen readers) to effectively communicate the alert’s content and functionality to users.

Keyboard Navigation

SweetAlert2 supports keyboard navigation. Users can:

This keyboard support allows users who cannot use a mouse to interact with the alerts effectively.

Screen Reader Compatibility

SweetAlert2 is designed to be compatible with screen readers. The use of appropriate ARIA attributes ensures that screen reader users can access and understand the alert’s content and functionality. This includes:

Regular testing with various screen readers is recommended to ensure consistent accessibility across different assistive technologies. Consider testing with multiple screen readers and users with visual impairments to gather feedback and address any potential usability issues.

Methods

SweetAlert2 provides several methods to interact with and manipulate active alerts. These methods allow for dynamic control over the alert’s behavior and content.

Swal.fire()

This is the primary method used to display a SweetAlert2 alert. It accepts an options object to configure the alert’s appearance and behavior. The method returns a Promise that resolves when the user interacts with the alert.

Swal.fire({
  title: 'Are you sure?',
  text: 'You won\'t be able to revert this!',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    // User clicked "Yes, delete it!"
  }
});

Swal.getPopup()

Returns the DOM element of the currently active SweetAlert2 popup. This allows direct manipulation of the alert’s HTML elements using DOM methods. Returns null if no alert is currently shown.

const popup = Swal.getPopup();
if (popup) {
  popup.style.backgroundColor = 'lightblue'; // Example: Change background color
}

Swal.isVisible()

Returns true if a SweetAlert2 alert is currently visible; otherwise, returns false.

if (Swal.isVisible()) {
  console.log('An alert is visible.');
}

Swal.close()

Closes the currently active SweetAlert2 alert. If no alert is active, it does nothing.

Swal.close();

Swal.clickConfirm()

Simulates a click on the confirm button of the active alert. Useful for automated testing or specific scenarios where you need to programmatically confirm an alert.

Swal.clickConfirm();

Swal.clickDeny()

Simulates a click on the deny button (if present) of the active alert.

Swal.clickDeny();

Swal.clickCancel()

Simulates a click on the cancel button (if present) of the active alert.

Swal.clickCancel();

Swal.showLoading()

Displays a loading indicator in the currently active alert. Useful when performing asynchronous operations within an alert.

Swal.showLoading();
// Perform asynchronous operation...
Swal.hideLoading(); //Call hideLoading after the operation is done

Swal.hideLoading()

Hides the loading indicator from the currently active alert.

Swal.hideLoading();

Swal.disableButtons()

Disables all buttons in the currently active alert. This prevents the user from interacting with the buttons until they are re-enabled.

Swal.disableButtons();
// ...some code...
Swal.enableButtons();

Swal.enableButtons()

Re-enables all buttons in the currently active alert, allowing user interaction.

Swal.enableButtons();

Swal.showValidationMessage()

Displays a validation message below an input field. This is primarily used with input-type alerts to provide feedback on invalid input.

Swal.showValidationMessage('Please enter a valid email address.');

Swal.resetValidationMessage()

Removes any validation message previously displayed using Swal.showValidationMessage().

Swal.resetValidationMessage();

Swal.update()

Updates the parameters of the currently active alert. This allows you to dynamically modify the alert’s content, title, icon, or other properties after it has been displayed.

Swal.update({
  title: 'Updated Title',
  text: 'This alert has been updated.'
});

Remember to handle potential errors (e.g., calling these methods when no alert is active) in a production environment to prevent unexpected behavior. Always check if an alert is visible using Swal.isVisible() before attempting to manipulate it.

Examples

This section provides practical examples demonstrating various SweetAlert2 functionalities.

Basic Alerts

Simple alerts to display information to the user.

// Success alert
Swal.fire({
  icon: 'success',
  title: 'Success!',
  text: 'Your operation was successful.'
});

// Error alert
Swal.fire({
  icon: 'error',
  title: 'Error!',
  text: 'An error occurred. Please try again.'
});

// Info alert
Swal.fire({
  icon: 'info',
  title: 'Information',
  text: 'Here is some important information.'
});

// Warning alert
Swal.fire({
  icon: 'warning',
  title: 'Warning!',
  text: 'Are you sure you want to proceed?'
});

//Alert without icon
Swal.fire('Hello World!');

Confirmation Dialogs

Alerts that require user confirmation before proceeding.

Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  }
})

Input Prompts

Alerts that prompt the user to enter information.

Swal.fire({
  title: 'Enter your name',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Submit',
  showLoaderOnConfirm: true,
  preConfirm: (login) => {
    return fetch(`/api/user?login=${login}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire({
      title: `${result.value.name}`,
      text: `Your login was successful!`,
      icon: 'success'
    })
  }
})

Custom Animations

Alerts with customized entry and exit animations (requires custom CSS). This example is illustrative; you’ll need to create the actual CSS classes.

Swal.fire({
  customClass: {
    popup: 'animated bounceInUp',
    confirmButton: 'btn btn-success'
  },
  title: 'Custom Animation!',
  text: 'This alert uses a custom animation'
})

(Remember to define .animated.bounceInUp and .btn.btn-success in your CSS.)

Loading Indicators

Alerts that show a loading indicator while performing asynchronous operations.

Swal.fire({
  title: 'Please wait...',
  allowEscapeKey: false,
  allowOutsideClick: false,
  didOpen: () => {
    Swal.showLoading()
  },
  timer: 2000
}).then(
  () => {
    Swal.fire({
      title: 'Success',
      icon: 'success'
    })
  }
)

Error Handling

Alerts for displaying error messages.

try {
  // Some code that might throw an error
  // ...
} catch (error) {
  Swal.fire({
    icon: 'error',
    title: 'Oops...',
    text: `An error occurred: ${error.message}`
  });
}

These examples provide a starting point. You can combine and modify these examples to create more complex and tailored alerts for your application. Remember to always consider user experience and accessibility when designing your alerts.

Migration Guide

This guide assists in migrating from older versions of SweetAlert or other alert libraries to SweetAlert2.

Upgrading from SweetAlert

SweetAlert and SweetAlert2 are distinct libraries with different APIs. Direct replacement isn’t possible; you’ll need to refactor your code. The core difference lies in the function call and options structure. SweetAlert used a function with multiple parameters, while SweetAlert2 uses a single function (Swal.fire()) with an options object.

SweetAlert (old):

swal("Here's a message!", "It's pretty, isn't it?");

SweetAlert2 (new):

Swal.fire("Here's a message!", "It's pretty, isn't it?"); //Simplest form
Swal.fire({
  title: "Here's a message!",
  text: "It's pretty, isn't it?"
}); //Using object for more customization.

All SweetAlert parameters need to be mapped to their SweetAlert2 equivalents within the options object. Consult the SweetAlert2 documentation for parameter details. Features like custom HTML, images, and callbacks need to be adapted to SweetAlert2’s syntax. The Promise-based then() method in SweetAlert2 is crucial for handling asynchronous operations and user responses.

Breaking Changes

SweetAlert2 introduces several breaking changes compared to SweetAlert and previous versions of SweetAlert2:

Thorough testing is essential after migration to ensure all functionality works as expected.

Compatibility

SweetAlert2 is designed to be compatible with modern browsers and JavaScript environments. However, very old browsers might require polyfills for features like Promises. SweetAlert2 generally aims for broad compatibility but always check the current browser support stated in the official documentation. If you need to support very old browsers, consider using a polyfill library for missing features. Always test your application thoroughly in the target browsers. The use of modules (via npm or similar) generally provides better compatibility and maintainability compared to using the CDN.