Quick summary: This practical guide covers installation, examples, confirmation dialogs, forms, file uploads, validation, async flows, and creating custom React alert hooks with SweetAlert2 — with copy-paste-ready code and best practices.
SweetAlert2 is a modern, highly configurable alert and modal library that replaces native alert dialogs with polished, accessible, and customizable UIs. When paired with React, SweetAlert2 lets you orchestrate synchronous and asynchronous flows—confirmations, multi-step modals, forms, and file uploads—without reinventing the wheel.
React developers often search for a React alert library that supports async handlers, validation, and custom styling. SweetAlert2 fits that bill: it exposes a promise-based API, flexible input types, and lifecycle hooks that integrate cleanly with functional components and hooks.
If you prefer an in-depth walkthrough, see an advanced example here: Advanced Alert Dialogs and Modals with SweetAlert2 in React. For official docs and latest options, the SweetAlert2 site is invaluable: sweetalert2.
Start with npm or yarn. SweetAlert2 is shipped as an ES module and plays nicely with bundlers. Install the core package and, if you prefer, the official React wrapper or use the core directly from your component.
// npm
npm install sweetalert2
// yarn
yarn add sweetalert2
For projects using a React wrapper, you can explore community packages, but importing SweetAlert2 directly is common because it gives full control and avoids extra dependencies. Example import:
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';
const MySwal = withReactContent(Swal);
Once imported, you can call Swals from event handlers or custom hooks. A tiny setup snippet below is a nice featured-snippet candidate for voice search queries like “how to install SweetAlert2 React”:
import Swal from 'sweetalert2';
// Basic alert
Swal.fire('Hello from SweetAlert2 in React!');
SweetAlert2 supports modal alerts and compact toasts. Alerts are modal by default and pause interaction with the page, while toasts are non-blocking notifications. You can tune position, timer, icons, and button text with simple options.
Toasts are useful for quick status messages (success, error) and are optimized for mobile. Alerts are better for confirmations and forms. Both support HTML content, custom classes, and animation settings, so you can match your app’s brand.
Example: a small React handler that triggers a success toast after an API call:
const notifySuccess = () => {
Swal.fire({
toast: true,
position: 'top-end',
icon: 'success',
title: 'Saved successfully',
showConfirmButton: false,
timer: 2500
});
}
SweetAlert2 inputs include text, email, textarea, select, radio, checkbox, and file. For forms, you can either collect a few fields via built-in inputs or render React components inside modals using the React wrapper (withReactContent). Validation can be synchronous or async, and you can show inline error messages with rejectable promises.
Built-in validation example: use preConfirm to validate values before the modal resolves. preConfirm can return a value (resolves) or throw/return a Promise.reject to keep the modal open and show an error.
Swal.fire({
title: 'Enter your email',
input: 'email',
inputLabel: 'Email address',
inputPlaceholder: 'you@example.com',
showCancelButton: true,
preConfirm: (value) => {
if (!value || !value.includes('@')) {
Swal.showValidationMessage('Please enter a valid email address');
return false;
}
return value;
}
}).then((result) => {
if (result.isConfirmed) {
console.log('Collected email:', result.value);
}
});
For complex forms you can use withReactContent to render a React form as the modal content, then handle submission via the modal’s confirm button. That approach keeps form state in React while leveraging SweetAlert2’s modal mechanics and animations.
Confirmation dialogs are a frequent use-case: deleting a record, submitting a payment, or confirming navigation. SweetAlert2 exposes a promise-based API that maps naturally to async/await, letting you pause flow until the user confirms.
Use clear button text and icons to improve UX, and handle cancellation paths explicitly. Because the API returns a promise with an object containing isConfirmed, isDenied, and isDismissed, you can branch cleanly in code.
const confirmDelete = async (id) => {
const result = await Swal.fire({
title: 'Delete item?',
text: 'This action cannot be undone.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Delete',
cancelButtonText: 'Cancel'
});
if (result.isConfirmed) {
await api.deleteItem(id); // your async deletion
Swal.fire('Deleted!', '', 'success');
} else {
Swal.fire('Cancelled', '', 'info');
}
};
Because this pattern uses async/await, it integrates cleanly with React event handlers and async hooks. It’s perfect for building predictable UX around destructive operations.
SweetAlert2 supports an input type of „file” that returns a FileList you can inspect. For small uploads (avatars, docs) you can handle the file in preConfirm and upload it via fetch or XHR while showing progress in the modal. For larger uploads, consider handing the file off to an asynchronous progress component and use the modal only for selection and confirmation.
When accepting files inside a modal, always validate file size and type client-side before uploading. This avoids unnecessary network traffic and gives immediate feedback through Swal.showValidationMessage.
Swal.fire({
title: 'Upload a file',
input: 'file',
inputAttributes: {
'accept': 'image/*',
'aria-label': 'Upload your profile picture'
},
preConfirm: file => {
if (!file) {
Swal.showValidationMessage('Select a file first');
return false;
}
if (file.size > 2_000_000) { // 2MB
Swal.showValidationMessage('File too large (max 2MB)');
return false;
}
// upload logic can go here
}
});
Wrap SweetAlert2 in a React hook to centralize alert patterns and keep components lean. A lightweight hook can expose functions like showAlert, confirm, toast, and showForm, and handle consistent styling and analytics across your app.
Example hook skeleton: keep the API small and predictable, returning promise-based functions so components can await user input. This reduces duplicate code and improves testability.
import Swal from 'sweetalert2';
export function useSwal() {
const alert = (options) => Swal.fire(options);
const confirm = (options) => Swal.fire({ ...options, showCancelButton: true });
const toast = (options) => Swal.fire({ toast: true, position:'top-end', ...options });
return { alert, confirm, toast };
}
Using hooks also lets you inject global configuration (button styles, icons, localization) from a single place, making theme changes trivial and consistent across your React app.
Validation: prefer preConfirm with both sync checks and async calls for server-side validation. Use Swal.showValidationMessage to communicate problems inline. Avoid blocking native form validation unless you have a clear replacement strategy.
Accessibility: SweetAlert2 manages focus and trapping, but you must still provide ARIA-compliant labels and accessible text alternatives — especially for file inputs and custom React content. Test with screen readers and keyboard-only navigation to ensure dialogs are operable and announcements are clear.
Best practices include keeping modals focused (limit content complexity inside a modal), preferring in-place controls for non-critical info, and using toasts for ephemeral feedback. For long forms or multi-step flows, consider a dedicated page or a layered modal with clear progress indicators.
If a modal doesn’t appear, check for CSS conflicts: SweetAlert2 injects default styles; a global reset or strict CSP could block inline styles. Also ensure SweetAlert2 is imported only once in your bundle to avoid duplicate global state.
For performance, avoid rendering heavy React trees inside the modal. Use React content only when necessary and clean up any event listeners or timers when the modal closes. Caching commonly used modal components can improve responsiveness.
If you need server-side rendering compatibility, conditionally import SweetAlert2 on the client (dynamic import) to avoid accessing window/document on the server.
npm install sweetalert2withReactContent(Swal) (optional)title, text, icon, input, showCancelButton, preConfirmOfficial, up-to-date configuration options and examples live on the SweetAlert2 docs: sweetalert2. For React-specific examples, community articles such as the one linked at Advanced Alert Dialogs and Modals with SweetAlert2 in React are excellent practical references.
For React fundamentals around state, effects, and hooks—useful when integrating modals—see the official React documentation: React docs. These resources provide patterns to combine component state with modal-driven flows.
When you need an npm-specific view (versions, changelog, peer deps), check the npm package page for SweetAlert2. Staying on recent versions ensures you get accessibility fixes, improved typings, and new input types.
Install with npm install sweetalert2 (or yarn add sweetalert2), import Swal into your component, and call Swal.fire({...}) inside event handlers. For React-specific rendering, use withReactContent(Swal) to render JSX inside modals.
Yes. Use the preConfirm option to run synchronous validation or return an async promise for server-side checks. Use Swal.showValidationMessage to surface validation errors without closing the modal.
SweetAlert2 manages focus trapping and basic ARIA behavior, but you must supply proper labels for inputs and test with screen readers. Keep modal content concise and ensure keyboard focus order is logical to maintain accessibility.
Further reading & references: