Search code examples
javascriptreactjsjsxsweetalert2

JSX instead of HTML in Sweet Alert


I would like to write JSX in Sweet Alert like so:

class TodoApp extends React.Component { 
  componentDidMount() {
    swal({
      html: <Welcome />
    });
  };

  render() {
    return <Welcome />;
  }
}

const Welcome = (props) => <p>Welcome to Sweet Alert and React</p>;

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

But I get Uncaught TypeError: t.html.cloneNode is not a function error.

How can I write JSX in Sweet Alert html?


Solution

  • From the docs

    In order to use SweetAlert with JSX syntax, you need to install SweetAlert with React. Note that you need to have both sweetalert and @sweetalert/with-react as dependencies in your package.json.

    You need to install @sweetalert/with-react,

    npm install @sweetalert/with-react --save
    
    

    Import

    import swal from '@sweetalert/with-react'
    

    And Usage

    swal(<Welcome />) //No need of `html` key
    
    

    Demo