React Sweet Alert step by step from installation.

 Here we will learn how to set up a react sweet alert and use react sweet alert in a react application. Below are the simple steps to implement the sweet alert in a react application.

Logo of Sweetalert

Steps are - 
  1. Installation of react sweet alert2 library
  2. Import Swal in a component and use 

Step 1. Installation: First we need to install the react sweet alert in a react application. It is effortless. Just need to run a single command. 

Command - 
npm i sweetalert2

Installation
Installation done



Step 2. Use of Sweetalert2: Installation completed. Now, we need to import Swal and use it in a component. 

Uses of sweetalert2
Implemented Sweetalert2


Here Sweetalert has been used during API calls for the POST method. This component is common to call all POST APIs. Therefore it shows a sweet alert message before submitting any screen of this application.

Final Output


Done 😃


Code 👇

import axios from 'axios';
import Swal from 'sweetalert2';

export const postData = (url, jsonData) => {
  return Swal.fire({
    title: 'Are you sure to procced.?',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes',
  }).then(async (result) => {
    if (result.isConfirmed) {
      try {
        const response = await axios.post(url, jsonData, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        return response.data;
      } catch (error) {
        throw new Error('Error posting data');
      }
    }
  });
};
export default {
    postData
};

Post a Comment

0 Comments