Blog

sweetalert2-react-content: React Alerts & Modals — Setup & Examples





sweetalert2-react-content: React Alerts & Modals — Setup & Examples


sweetalert2-react-content: React Alerts & Modals — Setup & Examples

Practical guide to using sweetalert2-react-content for React alert dialogs, interactive forms, hooks, and state integration. Includes code samples and best practices.

Overview: what sweetalert2-react-content gives you

sweetalert2-react-content is a small adapter that lets you mount React elements inside SweetAlert2 modals. Use it when you need the visual polish and features of SweetAlert2 plus the declarative power of JSX and React components. Instead of raw HTML strings, you can pass JSX nodes as title or html, and SweetAlert2 will render them as React components.

This approach is ideal for interactive alerts — confirm dialogs that contain React-controlled form fields, small wizard steps, or dynamic UI fragments. It keeps the modal UI consistent with the rest of your React app while leveraging SweetAlert2’s configuration, animation, and validation hooks.

In production you’ll use it alongside sweetalert2 itself. The adapter does one job: bridge SweetAlert2’s mounting with React’s render pipeline. That means your React logic stays idiomatic (props, state, hooks) while the modal lifecycle is driven by SweetAlert2.

Installation & quick setup

Install the two packages via npm or yarn. You need the core sweetalert2 and the React adapter sweetalert2-react-content:

npm install sweetalert2 sweetalert2-react-content
# or
yarn add sweetalert2 sweetalert2-react-content

Then create a wrapped instance in your module scope. This example shows the recommended import pattern and a minimal call:

import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content'

const MySwal = withReactContent(Swal)

// simple JSX usage
MySwal.fire({
  title: <p>React inside SweetAlert2</p>,
  html: <div><strong>JSX</strong> content here</div>
})

Important: keep the wrapped Swal instance (here MySwal) in a module-level variable or a stable ref so you don’t recreate the adapter each render. Recreating it can cause memory churn and multiple mounts across renders.

Helpful back-links: official SweetAlert2 docs (SweetAlert2) and the adapter repo (sweetalert2-react-content).

Basic example: alert with a React component

Below is a concise example showing a React component passed into SweetAlert2 via the adapter. This pattern is perfect for static JSX (icons, formatted text) and small interactive bits whose internal state is self-contained.

// MyAlert.js
import React from 'react'
import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content'

const MySwal = withReactContent(Swal)

export function showHello() {
  MySwal.fire({
    title: <p style={{color:'#0b66ff'}}>Hello from React!</p>,
    html: <div><strong>This is JSX content</strong></div>,
    showCloseButton: true
  })
}

Call showHello() from any component event handler. The JSX you pass is rendered as a React subtree and receives lifecycle behavior like any other React component.

Because you retain JSX, you can re-use internal components, styled elements, or even theme tokens from your component library to keep the modal consistent with your app’s design system.

Interactive alerts and form modals

Interactive alerts commonly need input validation. SweetAlert2 provides preConfirm, which runs before the dialog resolves. When using React content, the simplest robust pattern is to render input elements in the modal and use preConfirm to read their values from the DOM.

Example: a small name prompt with validation. This is a pragmatic approach that avoids complex cross-component wiring and works well with controlled/uncontrolled inputs inside the modal.

function askName() {
  MySwal.fire({
    title: 'Enter your name',
    html: <input id="swal-input-name" className="swal2-input" />,
    focusConfirm: false,
    preConfirm: () => {
      const name = document.getElementById('swal-input-name').value
      if (!name) {
        Swal.showValidationMessage('Please type your name')
      }
      return name
    }
  }).then(result => {
    if (result.isConfirmed) {
      console.log('Name:', result.value)
    }
  })
}

Why this pattern? It avoids trying to serialize component state across SweetAlert2 boundaries. For slightly more advanced forms you can render multiple inputs and validate them inside preConfirm, returning an object when valid.

If you want fully React-controlled forms inside the modal (useState, validation libraries), you can still do it: have your embedded form dispatch values to the DOM (hidden input or custom event) and read them in preConfirm, or design the form to call a callback that triggers SweetAlert2’s confirm programmatically. Both approaches are workable; choose whichever fits your architecture and testing strategy.

Hooks, state, and React integration patterns

Because SweetAlert2 mounts modals outside your component tree, it doesn’t automatically use React state flows. Keep modal triggers in React (useCallback, event handlers) and keep the adapter instance stable via useRef or module scope. Do not recreate the adapter in render or effect cleanup loops.

Pattern: create the adapter once in a module or inside an effect with an empty dependency array, then call it from event handlers. This keeps your hooks predictable and avoids double-mount behavior in development mode (React StrictMode can render effects twice).

For cases where modal actions update app state, resolve the modal promise and then dispatch state changes from the calling component. Example: call MySwal.fire(...).then(result => { if (result.isConfirmed) setName(result.value) }). This keeps side effects in React hooks rather than inside modal internals.

Best practices, accessibility, and alternatives

SweetAlert2 is polished, but it is not a full accessibility solution out-of-the-box for highly interactive forms. Use semantic inputs, proper labels, and test keyboard navigation (tab order, focus traps). Where accessibility requirements are strict, consider a dedicated React modal library that integrates ARIA patterns more tightly.

Keep these short rules in mind:

  • Mount the adapter once: use module scope or a stable ref.
  • Prefer preConfirm + DOM reads for quick forms; use callbacks/events for complex forms.
  • Always test in keyboard-only and screen-reader scenarios.

Alternatives if you need deeper React integration: libraries like React Modal or Radix UI Dialog provide fine-grained control and full React-managed DOM for complex interactive flows. But for quick confirmations, alerts, and small modals, SweetAlert2 + sweetalert2-react-content offers a great trade-off between speed and polish.

Examples roundup (snippets you can copy)

Three bite-sized patterns you’ll reuse:

  • Notification: simple JSX title & html for styled alerts.
  • Prompt: input element in JSX + preConfirm for validation.
  • Confirm with component: confirmation UI with dynamic content (pass JSX and use result.then to act).

Copy the code snippets above into a helper module and export functions like showHello, askName or confirmDelete. That keeps your components clean and centralizes modal behavior.

If you want a ready tutorial, the community article on dev.to provides a practical walk-through: Using React components in SweetAlert2 with sweetalert2-react-content.

SEO & snippet-ready summary

Need a quick copy for a featured snippet or voice search? Use this one-sentence answer:

Use sweetalert2-react-content to mount React JSX inside SweetAlert2 modals — install both packages, wrap Swal with withReactContent(Swal), then pass JSX to the title or html options and use preConfirm to validate inputs.

For voice search, shorter queries like “how to use sweetalert2-react-content” or “React alert dialogs example” will match this concise answer and the code examples above.

FAQ

1. How do I install and get started with sweetalert2-react-content?

Install both packages: npm install sweetalert2 sweetalert2-react-content. Import and wrap SweetAlert2: const MySwal = withReactContent(Swal). Then call MySwal.fire({ title: <p>...</p>, html: <MyComponent /> }). Keep the adapter instance stable in module scope or a ref.

2. Can I put form inputs in a JSX modal and validate them?

Yes. A simple reliable pattern is to render inputs in the modal and use preConfirm to read and validate values from the DOM (e.g., document.getElementById). For fully controlled React forms, use custom events or callbacks to pass results to preConfirm or programmatically close the modal after submission.

3. Will sweetalert2-react-content work with React hooks and controlled components?

It will, but remember the modal mounts outside your regular tree. Use hooks in the embedded components, but manage app-level state updates after the modal promise resolves. Keep the adapter stable and avoid recreating it inside render loops or strict-mode double-render pitfalls.

Semantic core (grouped keywords)

This semantic core is optimized for intent: primary, secondary, and clarifying query groups. Use them naturally in headings, metadata, and the first 150 words on your page.


Primary (high intent)
- sweetalert2-react-content
- React alert dialogs
- React modal components
- React interactive alerts
- sweetalert2-react-content installation
- sweetalert2-react-content tutorial

Secondary (medium intent)
- sweetalert2-react-content example
- sweetalert2-react-content setup
- sweetalert2-react-content hooks
- React form modals
- React alert forms
- React modal library

Clarifying / LSI phrases
- using React components in alerts
- sweetalert2 react adapter
- Swift setup sweetalert2 react
- interactive alert dialogs React
- sweetalert2 preConfirm example
- mounting JSX in SweetAlert2
- react modal form example
- sweetalert2-react-content getting started
- react modal state management
- react-controlled form in modal
  

Suggested micro-markup (FAQ schema)

Include this JSON-LD near the end of your HTML to improve chances of rich results for the FAQ. Replace question/answer text if you change FAQs.

{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "How do I install and get started with sweetalert2-react-content?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Install sweetalert2 and sweetalert2-react-content, wrap Swal with withReactContent(Swal), then pass JSX to title or html options. Keep the adapter instance stable."
      }
    },
    {
      "@type": "Question",
      "name": "Can I put form inputs in a JSX modal and validate them?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes. Render inputs in the modal and use preConfirm to read/validate DOM values, or wire callbacks/events for fully controlled React forms."
      }
    },
    {
      "@type": "Question",
      "name": "Will sweetalert2-react-content work with React hooks and controlled components?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes. Use hooks in embedded components but manage app-level state after the modal promise resolves and keep the adapter stable to avoid re-mount issues."
      }
    }
  ]
}


Scroll to top