-
Notifications
You must be signed in to change notification settings - Fork 3
/
SnackbarProvider.tsx
69 lines (62 loc) · 1.95 KB
/
SnackbarProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import Snackbar, { SnackbarProps } from "../Snackbar";
import SnackbarContext, { SnackbarContextType } from "./SnackbarContext";
import React from "react";
import { SnackbarProviderProps } from "./SnackbarProvider.types";
type SnackbarStateType = {
message: SnackbarProps["message"];
variant: SnackbarProps["variant"];
autoHideDuration?: SnackbarProps["autoHideDuration"];
actionText?: SnackbarProps["actionText"];
actionCallback?: SnackbarProps["actionCallback"];
open: boolean;
};
/**
* A helper component for adding a snackbar to an application. Injects a single snackbar component in your application, and exposes context down the React tree to control the snackbar via the useSnackbar hook. It should preferably be used at the root of your component tree.
*/
export default function SnackbarProvider({ children }: SnackbarProviderProps) {
// snackbar state
const [snackbar, setSnackbar] = React.useState<SnackbarStateType>({
actionCallback: () => {},
actionText: "",
message: "",
open: false,
variant: "info"
});
// close snackbar
const close = React.useCallback<SnackbarContextType["close"]>(
() =>
setSnackbar(snackbar => ({
...snackbar,
open: false
})),
[setSnackbar]
);
// show snackbar
const show = React.useCallback<SnackbarContextType["show"]>(
(
message = "",
variant = "info",
autoHideDuration = null,
actionText = "",
actionCallback = () => {}
) =>
setSnackbar({
actionCallback,
actionText,
autoHideDuration,
message,
open: true,
variant
}),
[setSnackbar]
);
// memoise callbacks
const contextValue = React.useMemo(() => ({ close, show }), [close, show]);
// wrap snackbar component and children in provider
return (
<SnackbarContext.Provider value={contextValue}>
{children}
<Snackbar {...snackbar} onClose={close} />
</SnackbarContext.Provider>
);
}