Search code examples
reactjsexpresssweetalert2

Using sweetalerts2 with api calls


I have my frontend in react and backend in express, i want to use sweetalerts2 on the sign up/sign in page. I tried searching around the internet about how would I display an error alert using sweetalerts2, when the credentials are wrong, but I couldn't find anything. Could anybody shed some light on this?


Solution

  • You can use sweetalert2-react-content package, like in this example:

    import React from "react";
    import ReactDOM from "react-dom";
    import Swal from "sweetalert2";
    import withReactContent from "sweetalert2-react-content";
    
    const MySwal = withReactContent(Swal);
    
    class App extends React.Component {
    
      myAwesomeLoginFunction() {
        // make your API call here.
        // let's say it returns a status code of 200 if the login credentials are correct
        const status = 200;
    
        if (status === 200) {
          MySwal.fire({
            title: <p>Hello World</p>,
            type: "success",
            customClass: "animated tada"
          });
        } else {
          MySwal.fire({
            title: <p>Wrong password/email</p>,
            type: "error",
            customClass: "animated tada"
          });
        }
      }
    
      render() {
        return (
          <div className="App">
            <h2>Hello world!</h2>
            <button onClick={this.myAwesomeLoginFunction.bind(this)}>Login</button>
          </div>
        );
      }
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    And there are other React wrappers for sweetAlert2, like: