Skip to content

Migration from SweetAlert to SweetAlert2

Limon Monte edited this page Jan 19, 2019 · 21 revisions

Important! This guide describes migrating from SweetAlert 1.x to SweetAlert2. SweetAlert 2.x has a lot of breaking changes it's API is different from SweetAlert2.

1. IE support

By default SweetAlert2 doesn't support IE. To enable IE 11 support, include Promise polyfill:

<script src="https://cdn.jsdelivr.net/npm/promise-polyfill@7.1.0/dist/promise.min.js"></script>

2. Promise instead of callback function

SweetAlert:

swal(
  {title: 'Are you sure?', showCancelButton: true}, 
  function(isConfirm) {
    if (isConfirm) {
      // handle confirm
    } else {
      // handle all other cases
    }
  }
)

SweetAlert2:

Swal.fire({title: 'Are you sure?', showCancelButton: true}).then(result => {
  if (result.value) {
    // handle Confirm button click
    // result.value will contain `true` or the input value
  } else {
    // handle dismissals
    // result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
  }
})

3. Modal with input field

SweetAlert:

swal({
  ...
  type: 'input'
  ...
}, function(inputValue) { 
  ...
})

SweetAlert2:

Swal.fire({
  ...
  input: 'text' // can be also 'email', 'password', 'select', 'radio', 'checkbox', 'textarea', 'file'
  ...
}).then(function(result) { 
  // result.value will containt the input value
})

4. Custom HTML in the title and description

SweetAlert:

swal({
  title: '<span class="title">Title</span>',
  text: '<span class="text">HTML description</span>',
  html: true
})

SweetAlert2:

Swal.fire({
  title: '<span class="title">Title</span>',
  html: '<span class="text">HTML description</span>'
})

5. closeOnConfirm and closeOnCancel parameters replaced with preConfirm

SweetAlert:

swal({
  {... closeOnConfirm: false},
  function() {
    // perform AJAX request
  }
})

SweetAlert2:

Swal.fire({
  ...
  showLoaderOnConfirm: true,
  preConfirm: function() {
    return new Promise(function(resolve) {
      setTimeout(function() {
        resolve()
      }, 2000)
    })
  }
}).then(function() {
  Swal.fire('Ajax request finished!')
})

6. Reversed buttons order

If you want to keep the buttons order like it was in the original SweetAlert plugin (Confirm button on the right side) set the reverseButtons parameter to true:

const SwalWithReverseButtons = Swal.mixin({
  showCancelButton: true,
  reverseButtons: true
})

SwalWithReverseButtons.fire('Reversed buttons')