nestable-dropdown-context.tsx 828 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import {
  2. createContext,
  3. Dispatch,
  4. FC,
  5. SetStateAction,
  6. useEffect,
  7. useState,
  8. } from 'react'
  9. export type NestableDropdownContextType = {
  10. selected: string | null
  11. setSelected: Dispatch<SetStateAction<string | null>>
  12. menuId: string
  13. }
  14. export const NestableDropdownContext = createContext<
  15. NestableDropdownContextType | undefined
  16. >(undefined)
  17. export const NestableDropdownContextProvider: FC<
  18. React.PropsWithChildren<{ id: string }>
  19. > = ({ id, children }) => {
  20. const [selected, setSelected] = useState<string | null>(null)
  21. useEffect(() => {
  22. return () => {
  23. // unset selection on unmount
  24. setSelected(null)
  25. }
  26. }, [])
  27. return (
  28. <NestableDropdownContext.Provider
  29. value={{ selected, setSelected, menuId: id }}
  30. >
  31. {children}
  32. </NestableDropdownContext.Provider>
  33. )
  34. }