File size: 1,067 Bytes
4e1096a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// DropdownContext.tsx
import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react';

interface DropdownContextValue {
  openDropdownId: string | null;
  openDropdown: (id: string) => void;
  closeDropdown: (id: string) => void;
  closeAll: () => void;
}

const DropdownContext = createContext<DropdownContextValue | null>(null);

export const DropdownProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [openDropdownId, setOpenDropdownId] = useState<string | null>(null);

  const openDropdown = useCallback((id: string) => {
    setOpenDropdownId(id);
  }, []);

  const closeDropdown = useCallback((id: string) => {
    setOpenDropdownId((current) => (current === id ? null : current));
  }, []);

  const closeAll = useCallback(() => {
    setOpenDropdownId(null);
  }, []);

  return (
    <DropdownContext.Provider value={{ openDropdownId, openDropdown, closeDropdown, closeAll }}>
      {children}
    </DropdownContext.Provider>
  );
};

export const useDropdownContext = () => useContext(DropdownContext);