Integration Of SweetAlert2 In React

Introduction

 
SweetAlert2 is a beautiful replacement for JavaScript's popup. It automatically centers itself on the page and looks great; no matter if you're using a desktop computer, mobile, or tablet.
 
Displaying to your users a default JavaScript alert box that informs them about an error or message is a poor solution in the era of modern web development. The problem with the browser default alert boxes is that they are not very appealing. SweetAlert2 is one of the best alternatives for you. It's highly customizable according to the color combination and features of your application.
 
In this tutorial, you will learn about a React library called SweetAlert2 that allows us to create all kinds of alert messages which can be customized to match the look and feel of our own website.
 
Sweetalert2 is the 34th most popular package on jsDelivr, with 189,363,946 CDN hits in the last month.
 

Live Preview

 
https://codesandbox.io/s/2z40652vwj
 

Final Output

 
 Integration Of SweetAlert2 In React
 
Integration Of SweetAlert2 In React
 

Display a Simple SweetAlert Box in React

 
Create a React app

To create a React app, you must have Node 8.10.0 or later installed on your local machine. You can download Node.js from - https://nodejs.org/en/download/current/

To create a new app, you have to run one of the following commands.
 
npx create-react-app my-app
 
OR
 
npm init react-app my-app
 
OR
 
yarn create react-app my-app
 
After creating your app, you have to run the following commands.
  1. cd sweetalert
  2. npm install
  3. npm start

Install SweetAlert2

  1. npm install --save sweetalert2 sweetalert2-react-content  
Copy and paste the following code in your component.
  1. import React, { Component } from "react";  
  2. import Swal from "sweetalert2";  
  3.   
  4. export default class AlertSuccess extends Component {  
  5.   
  6.     constructor() {  
  7.         super();  
  8.         this.HandleClick = this.HandleClick.bind(this);  
  9.     }  
  10.   
  11.     HandleClick() {  
  12.         Swal.fire({  
  13.             title: 'Success',  
  14.             type: 'success',  
  15.             text: 'Your work has been saved.',  
  16.         });  
  17.     }  
  18.   
  19.     render() {  
  20.         return (  
  21.             <div>  
  22.                 <button class="btn btn-success" onClick={this.HandleClick}>  
  23.                     Show Success Alert  
  24.                 </button>  
  25.             </div>  
  26.         );  
  27.     }  
  28. }  

List of arguments with default value.

Here are the keys that you can use if you pass an object into sweetAlert2.

Argument Default valueDescription
title null The title of the modal. It can either be added to the object under the key "title" or passed as the first parameter of the function.
text null A description for the modal. It can either be added to the object under the key "text" or passed as the second parameter of the function.
html null An HTML description for the modal. If "text" and "HTML" parameters are provided at the same time, "text" will be used.
type null The type of modal. SweetAlert2 comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". It can either be put in the array under the key "type" or passed as the third parameter of the function.
customClass null A custom CSS class for the modal. It can be added to the object under the key "customClass".
animation true If set to false, modal CSS animation will be disabled.
allowOutsideClick true If set to false, the user can't dismiss the modal by clicking outside it.
allowEscapeKey true If set to true, the user can dismiss the modal by pressing the Escape key.
showConfirmButton true If set to false, a "Confirm"-button will not be shown. It can be useful when you're using custom HTML description.
showCancelButton false If set to true, a "Cancel"-button will be shown, which the user can click on to dismiss the modal.
confirmButtonText "OK" Use this to change the text on the "Confirm"-button.
cancelButtonText "Cancel" Use this to change the text on the "Cancel"-button.
confirmButtonColor "#3085d6" Use this to change the background color of the "Confirm"-button (must be a HEX value).
cancelButtonColor "#aaa" Use this to change the background color of the "Cancel"-button (must be a HEX value).
confirmButtonClass null A custom CSS class for the confirm button.
cancelButtonClass null A custom CSS class for the cancel button.
closeOnConfirm true Set to false if you want the modal to stay open even if the user presses the "Confirm"-button. This is especially useful if the function attached to the "Confirm"-button is another SweetAlert2.
imageUrl null Add a customized icon for the modal. Should contain a string with the path to the image.
imageSize "80x80" If imageUrl is set, you can specify imageSize to describes how big you want the icon to be in px. Pass in a string with two values separated by an "x". The first value is the width, the second is the height.
timer null Auto-close the timer of the modal. Set in ms (milliseconds).
width 500 Modal window width, including paddings (box-sizing: border-box).
padding 20 Modal window padding.
background "#fff"
Modal window background (CSS background property).
 
List of the methods. 
 
MethodDescription
Swal.isVisible() Determine if modal is shown.
Swal.mixin({ ...options }) Returns an extended version of `Swal` containing `params` as defaults. Useful for reusing Swal configuration.
Swal.update({ ...options }) Updates popup options.
Swal.close() Close the currently open SweetAlert2 modal programmatically, the Promise returned by Swal.fire() will be resolved with an empty object { }
Swal.getContainer() Get the popup container which contains the backdrop.
Swal.getHeader() Get the modal header. The header contains progress steps, the icon, the image, the title, and the close button.
Swal.getTitle() Get the modal title.
Swal.getCloseButton() Get the close button.
Swal.getContent() Get the modal content.
Swal.getImage() Get the image.
Swal.getActions() Get the actions block (buttons container).
Swal.getFooter() Get the modal footer.
Swal.getFocusableElements() Get all focusable elements in the popup.
Swal.getConfirmButton() Get the "Confirm" button.
Swal.getCancelButton() Get the "Cancel" button.
Swal.enableButtons() Enable "Confirm" and "Cancel" buttons.
Swal.disableButtons() Disable "Confirm" and "Cancel" buttons.
Swal.enableConfirmButton() Deprecated and will be removed in the next major release, use Swal.getConfirmButton()instead.
Enable the "Confirm"-button only.
Swal.disableConfirmButton() Deprecated and will be removed in the next major release, use Swal.getConfirmButton()instead.
Disable the "Confirm"-button only.
Swal.showLoading() or Swal.enableLoading() Disable buttons and show loader. This is useful with AJAX requests.
Swal.hideLoading() or Swal.disableLoading() Enable buttons and hide loader.
Swal.isLoading() Determine if modal is in the loading state. Related methods: Swal.showLoading() and Swal.hideLoading()
Swal.getTimerLeft() Returns the time left in case when timerparameter is set.
Swal.stopTimer() Stops the timer in case when timer parameter is set. Returns the time left
Swal.resumeTimer() Resume the timer previously stopped. Returns the time left
Swal.toggleTimer() Toggle state of the timer between stopped and running. Returns the time left
Swal.isTimerRunning() Returns the status of a timer: true if is running, false if it's paused
Swal.increaseTimer(n) Increase the timer by n milliseconds. Returns the time left
Swal.clickConfirm() Click the "Confirm"-button programmatically.
Swal.clickCancel() Click the "Cancel"-button programmatically.
Swal.getInput() Get the input DOM node, this method works with the input parameter.
Swal.disableInput() Disable input. A disabled input element is unusable and un-clickable.
Swal.enableInput() Enable input.
Swal.showValidationMessage(error) Show the validation message DOM node.
Swal.resetValidationMessage() Hide the validation message DOM node.
Swal.getValidationMessage() Get the validation message DOM node.
Swal.queue([Array]) Provide an array of SweetAlert2 parameters to show multiple modals, one modal after another.
Swal.getQueueStep() Get the index of current modal in the queue. When there's no active queue, null will be returned.
Swal.insertQueueStep() Insert a modal to queue, you can specify modal positioning with the second parameter. By default, a modal will be added to the end of a queue.
Swal.deleteQueueStep(index) Delete a modal at index from queue.
Swal.getProgressSteps() Progress steps getter.
Swal.setProgressSteps([]) Progress steps setter.
Swal.showProgressSteps() Show progress steps.
Swal.hideProgressSteps() Hide progress steps.
Swal.isValidParameter(param) Determine if parameter name is valid.
Swal.isUpdatableParameter(param) Determine if parameter name is valid for Swal.update() method.
 
You can download the code from the link given on the top of this article or preview the output and code from here.