diff --git a/README.md b/README.md index 807a197..a3eb688 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ There are lots of props to customize your toast or your can use renderToast to i offsetTop={30} offsetBottom={40} swipeEnabled={true} + dismissAllPreviousToast={true} // false by default enable this to show one toast at a time renderToast={(toastOptions) => JSX.Element} implement custom toast component. > ... diff --git a/src/toast-container.tsx b/src/toast-container.tsx index b0bce14..1210cb6 100644 --- a/src/toast-container.tsx +++ b/src/toast-container.tsx @@ -4,7 +4,8 @@ import { ViewStyle, KeyboardAvoidingView, Platform, - Dimensions, SafeAreaView, + Dimensions, + SafeAreaView, } from "react-native"; import Toast, { ToastOptions, ToastProps } from "./toast"; @@ -42,25 +43,34 @@ class ToastContainer extends Component { */ show = (message: string | JSX.Element, toastOptions?: ToastOptions) => { let id = toastOptions?.id || Math.random().toString(); + const onDestroy = () => { toastOptions?.onClose && toastOptions?.onClose(); this.setState({ toasts: this.state.toasts.filter((t) => t.id !== id) }); }; + const createdToast = { + id, + onDestroy, + message, + open: true, + onHide: () => this.hide(id), + ...this.props, + ...toastOptions, + }; + + const dismissAllPreviousToast = + createdToast.dismissAllPreviousToast || false; + + const openToasts = dismissAllPreviousToast + ? [] + : this.state.toasts.filter((t) => t.open); + + const constructedToastState = [createdToast, ...openToasts]; + requestAnimationFrame(() => { this.setState({ - toasts: [ - { - id, - onDestroy, - message, - open: true, - onHide: () => this.hide(id), - ...this.props, - ...toastOptions, - }, - ...this.state.toasts.filter((t) => t.open), - ], + toasts: constructedToastState, }); }); @@ -107,7 +117,7 @@ class ToastContainer extends Component { */ isOpen = (id: string) => { return this.state.toasts.some((t) => t.id === id && t.open); - } + }; renderBottomToasts() { const { toasts } = this.state; @@ -211,8 +221,10 @@ const styles = StyleSheet.create({ maxWidth: "100%", zIndex: 999999, elevation: 999999, - alignSelf: 'center', - ...(Platform.OS === "web" ? { overflow: "hidden", userSelect: 'none' } : null), + alignSelf: "center", + ...(Platform.OS === "web" + ? { overflow: "hidden", userSelect: "none" } + : null), }, message: { color: "#333", diff --git a/src/toast.tsx b/src/toast.tsx index 2e7556f..0931298 100644 --- a/src/toast.tsx +++ b/src/toast.tsx @@ -111,6 +111,12 @@ export interface ToastOptions { */ data?: any; + /** + * Dismiss previous toast + */ + + dismissAllPreviousToast?: boolean; + swipeEnabled?: boolean; }