global-alerts-context.tsx 978 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { createContext, FC, useCallback, useContext, useState } from 'react'
  2. const GlobalAlertsContext = createContext<HTMLDivElement | null | undefined>(
  3. undefined
  4. )
  5. export const GlobalAlertsProvider: FC<React.PropsWithChildren> = ({
  6. children,
  7. }) => {
  8. const [globalAlertsContainer, setGlobalAlertsContainer] =
  9. useState<HTMLDivElement | null>(null)
  10. const handleGlobalAlertsContainer = useCallback(
  11. (node: HTMLDivElement | null) => {
  12. setGlobalAlertsContainer(node)
  13. },
  14. []
  15. )
  16. return (
  17. <GlobalAlertsContext.Provider value={globalAlertsContainer}>
  18. <div className="global-alerts" ref={handleGlobalAlertsContainer} />
  19. {children}
  20. </GlobalAlertsContext.Provider>
  21. )
  22. }
  23. export const useGlobalAlertsContainer = () => {
  24. const context = useContext(GlobalAlertsContext)
  25. if (context === undefined) {
  26. throw new Error(
  27. 'useGlobalAlertsContainer is only available inside GlobalAlertsProvider'
  28. )
  29. }
  30. return context
  31. }