How to use Sweetalert2 in React-JS

First, you all need to install the following package

npm install sweetalert2

After installation, import all files which are required, you don’t need to import CSS file

import Button from 'mui-button';
import Swal from 'sweetalert2'; 
import './App.css';

Then write this code into your App.js file and then sweetalert should be working  : )

function App() {
  const onSave = () => {
    Swal.fire({
      title: 'Do you want to save the changes?',
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: 'Save',
      denyButtonText: `Don't save`,
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire('Saved!', '', 'success')
      } else if (result.isDenied) {
        Swal.fire('Changes are not saved', '', 'info')
      }
    })
  }
  const error = () => {
    Swal.fire({
      icon: 'error',
      title: 'Oops...',
      text: 'Something went wrong!',
    })
  }
  const custom = () => {
    Swal.fire({
      position: 'top-end',
      icon: 'success',
      title: 'Your work has been saved',
      showConfirmButton: false,
      timer: 1500
    })
  }
  const onDelete = () => {
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire(
          'Deleted!',
          'Your file has been deleted.',
          'success'
        )
      }
    })
  }
  return (
    <div className="App">
      <div><h1>Sweet Alert 2 in React-JS</h1></div>
      <div>
        <Button variant='outlined' color='error' onClick={onDelete}>Delete</Button>
        <Button variant='outlined' color='success' onClick={onSave}>Save Changes</Button>
        <Button variant='outlined' color='error' onClick={error}>Error</Button>
        <Button variant='outlined' color='default' onClick={custom}>Custom Position</Button>
      </div>
    </div>
  );
}

export default App;

Demo:

Hope this blog is informative for you : )

Thanks for reading

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories