react-high-toast
Version:
A highly customizable toast notification system for React using portals
45 lines (44 loc) • 1.93 kB
JavaScript
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import React, { createContext, useContext, useState } from 'react';
var ToastContext = createContext(undefined);
export var ToastProvider = function (_a) {
var children = _a.children;
var _b = useState([]), toasts = _b[0], setToasts = _b[1];
var addToast = function (message, options) {
var _a;
if (options === void 0) { options = {}; }
var id = options.id || Math.random().toString(36).substr(2, 9);
var toast = {
id: id,
message: message,
type: options.type || 'default',
duration: (_a = options.duration) !== null && _a !== void 0 ? _a : 5000,
position: options.position || 'top-right',
createdAt: Date.now(),
};
setToasts(function (prev) { return __spreadArray(__spreadArray([], prev, true), [toast], false); });
if (toast.duration !== 0) {
setTimeout(function () { return removeToast(id); }, toast.duration);
}
return id;
};
var removeToast = function (id) {
setToasts(function (prev) { return prev.filter(function (toast) { return toast.id !== id; }); });
};
return (React.createElement(ToastContext.Provider, { value: { toasts: toasts, addToast: addToast, removeToast: removeToast } }, children));
};
export var useToast = function () {
var context = useContext(ToastContext);
if (!context) {
throw new Error('useToast must be used within a ToastProvider');
}
return context;
};