-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMultiSelectContext.tsx
More file actions
76 lines (66 loc) · 2.2 KB
/
MultiSelectContext.tsx
File metadata and controls
76 lines (66 loc) · 2.2 KB
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
70
71
72
73
74
75
76
import React, { createContext, useContext, useState, ReactNode } from "react"
// Define the shape of our context
interface MultiSelectContextType {
selectedIds: number[]
toggleSelection: (selectedId: number) => void
resetSelection: () => void
handleBulkSelection: (selectedIds: number[], isSelectAll: boolean) => void
isGlobalSelection: boolean
enableGlobalSelection: () => void
disableGlobalSelection: () => void
}
// Create the context
const MultiSelectContext = createContext<MultiSelectContextType | undefined>(undefined)
// Context provider component
export const MultiSelectProvider = ({ children }: { children?: ReactNode }) => {
const [selectedIds, setSelectedIds] = useState<number[]>([])
const [isGlobalSelection, setIsGlobalSelection] = useState(false)
// Toggle individual selection
const toggleSelection = (selectedId: number) => {
setIsGlobalSelection(false)
setSelectedIds((prev) =>
prev.includes(selectedId) ? prev.filter((item) => item !== selectedId) : [...prev, selectedId]
)
}
// Handle bulk selection (select/deselect all)
const handleBulkSelection = (selectedIds: number[], isSelectAll: boolean) => {
setIsGlobalSelection(false)
setSelectedIds((prev) => (isSelectAll ? [...new Set([...prev, ...selectedIds])] : []))
}
// Add resetSelection to clear all selected IDs
const resetSelection = () => {
setIsGlobalSelection(false)
setSelectedIds([])
}
const enableGlobalSelection = () => {
setIsGlobalSelection(true)
setSelectedIds([])
}
const disableGlobalSelection = () => {
setIsGlobalSelection(false)
}
// Provide the selectedIds and the handler to children components
return (
<MultiSelectContext.Provider
value={{
selectedIds,
toggleSelection,
resetSelection,
handleBulkSelection,
isGlobalSelection,
enableGlobalSelection,
disableGlobalSelection,
}}
>
{children}
</MultiSelectContext.Provider>
)
}
// Custom hook to use the context
export const useMultiSelect = () => {
const context = useContext(MultiSelectContext)
if (!context) {
throw new Error("useMultiSelect must be used within a MultiSelectProvider")
}
return context
}