Last active
April 12, 2022 22:26
-
-
Save henev/1e369ee4f15f1ddb1eacfc96cb4771f0 to your computer and use it in GitHub Desktop.
Toast Provider Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useMemo } from 'react'; | |
import { createPortal } from 'react-dom'; | |
import { ToastContext } from './ToastContext'; | |
import { Toast } from './Toast'; | |
// Create a random ID | |
function generateUEID() { | |
let first = (Math.random() * 46656) | 0; | |
let second = (Math.random() * 46656) | 0; | |
first = ('000' + first.toString(36)).slice(-3); | |
second = ('000' + second.toString(36)).slice(-3); | |
return first + second; | |
} | |
export const ToastProvider = (props) => { | |
const [toasts, setToasts] = useState([]); | |
const open = (content) => | |
setToasts((currentToasts) => [ | |
...currentToasts, | |
{ id: generateUEID(), content }, | |
]); | |
const close = (id) => | |
setToasts((currentToasts) => | |
currentToasts.filter((toast) => toast.id !== id) | |
); | |
const contextValue = useMemo(() => ({ open }), []); | |
return ( | |
<ToastContext.Provider value={contextValue}> | |
{props.children} | |
{createPortal( | |
<div className="toasts-wrapper"> | |
{toasts.map((toast) => ( | |
<Toast key={toast.id} close={() => close(toast.id)}> | |
{toast.content} | |
</Toast> | |
))} | |
</div>, | |
document.body | |
)} | |
</ToastContext.Provider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment