Skip to content
nexus-dialogs
GitHub npm

Migrate from SweetAlert2

Two paths: change only the import and migrate little by little, or go straight to the native API. You can mix both in the same project.

Path 1: change the import

The nexus-dialogs/swal adapter accepts the code you already have: Swal.fire, mixin, toasts, inputs, preConfirm, steps, timers and the query methods. It applies the library’s button standard.

// before
import Swal from 'sweetalert2'
// after
import Swal from 'nexus-dialogs/swal'

Without a bundler, replace the <script> with this one (it defines window.Swal):

<script src="https://cdn.jsdelivr.net/npm/nexus-dialogs/dist/nexus-dialogs.swal.iife.js"></script>

Path 2: the native API

Shorter, with precise types and ready-made recipes (confirmDelete, unsavedChanges, approval, bulkAction…). Each example has both buttons: the first runs the SweetAlert2 code through the adapter, the second the native version.

The result appears here.

Confirm a delete

The most common case. The adapter turns the button red and puts focus on “Cancel” because the text says “delete”.

Before: SweetAlert2

const r = await Swal.fire({
  title: 'Delete Laura Méndez?',
  text: "You won't be able to revert this",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete',
})
if (r.isConfirmed) await remove(id)

After: native API

import { confirmDelete } from 'nexus-dialogs/patterns'

if (await confirmDelete({ what: 'Laura Méndez' })) await remove(id)

Success notice that closes by itself

The timer pauses with the mouse or focus over it, and “reduce motion” is respected.

Before: SweetAlert2

await Swal.fire({
  icon: 'success',
  title: 'Saved',
  text: 'The changes are now in the system',
  timer: 2500,
  showConfirmButton: false,
})

After: native API

import { dialog } from 'nexus-dialogs'

await dialog.success({ title: 'Saved', text: 'The changes are now in the system', timer: 2500 })

Ask for a value with validation

inputValidator becomes `validate`; the error stays tied to the field and is announced to screen readers.

Before: SweetAlert2

const { value: email } = await Swal.fire({
  title: 'Customer email',
  input: 'email',
  inputValidator: (v) => (!v ? 'Enter an email' : undefined),
})
if (email) await send(email)

After: native API

import { form } from 'nexus-dialogs/forms'

const r = await form({
  title: 'Customer email',
  fields: [{ name: 'email', label: 'Email', type: 'email', required: true }],
})
if (r.confirmed) await send(r.value.email)

Form with several fields

In SweetAlert2 it is built with HTML and preConfirm reading the DOM. Here the fields are data and validation goes per field.

Before: SweetAlert2

const { value } = await Swal.fire({
  title: 'New expense',
  html: '<input id="rfc" class="swal2-input"><input id="amount" class="swal2-input">',
  focusConfirm: false,
  preConfirm: () => ({
    rfc: document.getElementById('rfc').value,
    amount: document.getElementById('amount').value,
  }),
})

After: native API

import { form } from 'nexus-dialogs/forms'

const r = await form({
  title: 'New expense',
  fields: [
    { name: 'rfc', label: 'Supplier RFC', type: 'rfc', required: true },
    { name: 'amount', label: 'Amount', type: 'money', required: true },
  ],
})

Several steps

progressSteps and `Swal.mixin().queue` become a wizard with a final review and accessible progress.

Before: SweetAlert2

const Steps = Swal.mixin({ progressSteps: ['1', '2', '3'], confirmButtonText: 'Next' })
await Steps.fire({ title: 'Details', currentProgressStep: 0 })
await Steps.fire({ title: 'Position', currentProgressStep: 1 })
await Steps.fire({ title: 'Benefits', currentProgressStep: 2 })

After: native API

import { wizard } from 'nexus-dialogs/forms'

const r = await wizard({
  title: 'New employee',
  review: true,
  steps: [
    { title: 'Details', fields: [{ name: 'name', label: 'Name', required: true }] },
    { title: 'Position', fields: [{ name: 'position', label: 'Position', required: true }] },
    { title: 'Benefits', fields: [{ name: 'vouchers', label: 'Food vouchers', type: 'switch' }] },
  ],
})

Toast notice

Toasts share a queue and are announced in a live region. They support an “Undo” action.

Before: SweetAlert2

Swal.fire({
  toast: true,
  position: 'top-end',
  icon: 'success',
  title: 'Employee saved',
  timer: 3000,
  showConfirmButton: false,
})

After: native API

import { toast } from 'nexus-dialogs/toast'

toast.success('Employee saved', { action: { label: 'Undo', onClick: undo } })

Long operation with “Loading…”

An async preConfirm shows “Processing…”; if the promise fails, the error appears inside the dialog and it does not close.

Before: SweetAlert2

const r = await Swal.fire({
  title: 'Send to be stamped?',
  showCancelButton: true,
  showLoaderOnConfirm: true,
  preConfirm: () => stamp().catch((e) => Swal.showValidationMessage(e.message)),
})

After: native API

import { dialog } from 'nexus-dialogs'

const r = await dialog.confirm({
  title: 'Send to be stamped?',
  preConfirm: () => stamp(), // if it throws, the error is shown and the dialog stays open
})

Equivalences

SweetAlert2nexus-dialogs
Swal.fire({ icon, title, text })dialog.success / error / warning / info
showCancelButton + isConfirmeddialog.confirm(…) → r.confirmed
input + inputValidatorform({ fields }) with required, validate
html + preConfirm reading the DOMform, data in r.value
progressSteps / queuewizard({ steps, review })
toast: truetoast.success / error / info
showLoaderOnConfirm + preConfirmasync preConfirm (shows “Processing…”)
timer, timerProgressBartimer (pauses with mouse or focus)
result.isDismissed, dismissr.reason (cancel, escape, backdrop, timer, program)
Swal.close()dialog.close() / dialog.closeAll()
Swal.mixin(defaults)configure({ defaults })
theme, customClassconfigure({ theme, scheme }) and --nd-* variables

What changes on purpose

Behavior differences worth reviewing

A compatible API doesn’t mean everything is interchangeable. These are the differences that affect code that already works.

With SweetAlert2With nexus-dialogs/swalWhat to do
footer accepts HTMLThe footer is shown as plain text (tags are stripped).Put the link or formatting inside html.
An html string is interpretedIt is shown as text by default (strictHtml). See Security.configure({ strictHtml: false }) with your own content, or configure({ sanitize }) if it is not.
The content is in the documentIt is inside a Shadow DOM: document.getElementById does not find it.Use Swal.getHtmlContainer().querySelector(…).
Page CSS (Bootstrap, .swal2-*) changes its lookThe page CSS no longer gets in; the look comes from the theme.Use configure({ theme }) or a ready-made theme.
confirmButtonColor, customClass, background, backdrop…They are accepted and ignored.Remove those options; one color per intent.
Order and focus of free buttonsAlways Cancel, Deny, Confirm; a “delete” button switches to danger by itself and focus starts on Cancel.Review the deletes; force with danger: true or reverseButtons.
Default texts in EnglishThey come out in the configured language.configure({ lang }) or labels.
Toasts with their own positions and stackingThey use the nexus-dialogs/toast queue, a single position for all.Check where you expected to see them.
showClass, hideClass, animation, topLayer, Swal.versionThey don’t exist.Motion comes from the theme and respects “reduce motion”.
template with <swal-function-param>It is not accepted.Pass the function through the options.

Checklist

  1. Install nexus-dialogs and change the import (or the <script>).
  2. If you use html, add configure({ strictHtml: false }) once (your own content) or configure({ sanitize }) (outside content).
  3. Search your code for document.getElementById or querySelector inside html: and didOpen; replace them with Swal.getHtmlContainer().
  4. Remove customClass and confirmButtonColor; set a theme once with configure.
  5. Review the delete dialogs: focus now starts on “Cancel”.
  6. Migrate first what repeats the most (delete, save, forms) to the recipes and to form.
  7. Test with the keyboard: Tab, Esc and focus returning to the button that opened the dialog.

Missing something? The full list of what the adapter covers is in the Guide.