@scrumble-nl/react-quick-toaster
Version:
A quick and easy wrapper around react-bootstrap toasters, you can toast from anywhere in your application with a few simple steps.
49 lines (48 loc) • 1.91 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { ToastRenderer } from './toast-renderer';
import './scss/toaster.css';
export const ToastContext = React.createContext({
add: () => {
// Default implementation does nothing
},
});
export const isIToast = (toast) => {
return 'id' in toast;
};
export class ToastProvider extends React.Component {
constructor() {
super(...arguments);
this.state = { toasts: [] };
this.addToast = (toast) => {
if (this.state.toasts.length >= this.props.maxItems) {
this.removeToastByIndex(0, this.state.toasts.length - this.props.maxItems + 1);
}
this.setState({
toasts: [Object.assign(Object.assign({}, toast), { id: isIToast(toast) ? toast.id : new Date().getTime() }), ...this.state.toasts],
});
};
this.removeToastByIndex = (index, deleteCount = 1) => {
const toasts = this.state.toasts;
toasts.splice(index, deleteCount);
this.setState({ toasts: toasts });
};
this.removeToastById = (id) => {
for (let i = 0, j = this.state.toasts.length; i < j; i++) {
if (this.state.toasts[i].id === id) {
this.removeToastByIndex(i);
return;
}
}
};
this.render = () => {
const context = { add: this.addToast };
return (_jsxs(ToastContext.Provider, Object.assign({ value: context }, { children: [this.props.children, _jsx(ToastRenderer, { toasts: this.state.toasts, position: this.props.position, defaultTimer: this.props.defaultTimer, removeToast: this.removeToastById.bind(this) })] })));
};
}
}
ToastProvider.defaultProps = {
position: 'top-right',
maxItems: 8,
defaultTimer: 4000,
};