UNPKG

react-toastly

Version:

A beautiful React toast notification library with animations, gradients, sounds, and premium features for free.

56 lines (47 loc) 1.52 kB
import React, { createContext, useContext, useState, useEffect, useRef } from "react"; import './index.css'; const ToastContext = createContext(); export const ToastlyProvider = ({ children }) => { const [toasts, setToasts] = useState([]); const timers = useRef({}); // Keep track of timers for cleanup const addToast = (message) => { const id = Date.now() + Math.random(); setToasts((prev) => [...prev, { id, message }]); timers.current[id] = setTimeout(() => { setToasts((prev) => prev.filter((t) => t.id !== id)); delete timers.current[id]; }, 3000); }; // Cleanup timers on unmount to prevent memory leaks useEffect(() => { return () => { Object.values(timers.current).forEach(clearTimeout); }; }, []); const success = (message) => { addToast(message); }; return ( <ToastContext.Provider value={{ success }}> {children} <div className="fixed top-4 right-4 space-y-2 z-50"> {toasts.map(({ id, message }) => ( <div key={id} className="bg-gradient-to-r from-purple-500 to-pink-500 text-white p-3 rounded-lg shadow-lg animate-slideIn" style={{ minWidth: "250px" }} > {message} </div> ))} </div> </ToastContext.Provider> ); }; export const useToastly = () => { const context = useContext(ToastContext); if (!context) { throw new Error("useToastly must be used within a ToastlyProvider"); } return context; };