5/25/2023

How to Create Custom Notification Component in React Using SweetAlert 2023

 How to Create Custom Notification Component in React Using SweetAlert

Here are the steps to create a custom notification component in React using SweetAlert:Chuwi ubook x

  1. Install SweetAlert:

npm install sweetalert

  1. Import SweetAlert in the component:

import Swal from 'sweetalert'

  1. Create the Notification component:Chuwi hipad max

jsx
const Notification = (type, message) => {
  Swal({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000,  
    timerProgressBar: true,
    text: message,  
    background: type === 'success' ? '#90EE90' : '#FF0000'      
  })
}
  1. Call the component to show notifications:
jsx
Notification('success', 'Task completed successfully!')

Notification('error', 'Oops, something went wrong!')
  1. Pass the message and type props:
  • success - Shows a green notification
  • error - Shows a red notification
  1. Import and use the Notification component:
jsx
import { Notification } from './Notification'

// Call from a function
function handleClick() {
  Notification('success', 'Task added!')
}
  1. SweetAlert will show a notification at the top of the page with:
  • A dismissable timer
  • Custom background color based on type
  • No confirmation button

This gives you a simple way to show custom notification alerts in any React component using SweetAlert. Let me know if you have any other questions!

No comments:

Post a Comment