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 = () => {{
      title: 'Do you want to save the changes?',
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: 'Save',
      denyButtonText: `Don't save`,
    }).then((result) => {
      if (result.isConfirmed) {'Saved!', '', 'success')
      } else if (result.isDenied) {'Changes are not saved', '', 'info')
  const error = () => {{
      icon: 'error',
      title: 'Oops...',
      text: 'Something went wrong!',
  const custom = () => {{
      position: 'top-end',
      icon: 'success',
      title: 'Your work has been saved',
      showConfirmButton: false,
      timer: 1500
  const onDelete = () => {{
      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) {
          'Your file has been deleted.',
  return (
    <div className="App">
      <div><h1>Sweet Alert 2 in React-JS</h1></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>

export default App;


Hope this blog is informative for you : )

Thanks for reading

Submit a Comment

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


Select Categories