-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathArrayWrapper.tsx
44 lines (38 loc) · 1.41 KB
/
ArrayWrapper.tsx
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { FC, ReactNode, useState, createContext, useEffect } from 'react'
type FilterArray = [any[], boolean]
export const FilterArrayContext = createContext<FilterArray>([[], false])
enum State {
ShowAll = 'Show All',
ShowLess = 'Show Less',
}
export const ArrayWrapper: FC<{ array: any[]; children: ReactNode; minimum: number }> = ({
array: originalArray,
children,
minimum,
}) => {
const [showAll, setShowAll] = useState(false)
const [filteredArray, setFilteredArray] = useState([...originalArray])
useEffect(() => {
if (showAll) {
setFilteredArray(originalArray)
} else {
setFilteredArray(originalArray.slice(0, minimum))
}
}, [showAll, originalArray, minimum])
return (
<FilterArrayContext.Provider value={[filteredArray, showAll]}>
<div className='d-flex flex-column flex-items-start'>
{originalArray.length > minimum && (
<button
onClick={() => setShowAll((prev) => !prev)}
className='border-0 color-bg-transparent color-fg-accent underline mb-2'
>
{showAll ? State.ShowLess : State.ShowAll}
</button>
)}
{children}
</div>
</FilterArrayContext.Provider>
)
}