-
-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathuseSelectCommon.tsx
More file actions
82 lines (73 loc) · 1.85 KB
/
Copy pathuseSelectCommon.tsx
File metadata and controls
82 lines (73 loc) · 1.85 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
77
78
79
80
81
82
import React, { useMemo } from 'react';
import useControlledOrUncontrolled from '../common/hooks/useControlledOrUncontrolled';
import {
StyledDropdownButton,
StyledDropdownIcon,
StyledFlatSelectWrapper,
StyledSelectWrapper
} from './Select.styles';
import { SelectCommonProps, SelectOption } from './Select.types';
const emptyArray: [] = [];
export const useSelectCommon = <T,>({
className,
defaultValue,
disabled,
native,
onChange,
options: optionsProp = emptyArray,
readOnly,
style,
value: valueProp,
variant,
width
}: { native: boolean } & SelectCommonProps<T>) => {
const options = useMemo(
() => optionsProp.filter(Boolean) as SelectOption<T>[],
[optionsProp]
);
const [value, setValue] = useControlledOrUncontrolled({
defaultValue: defaultValue ?? options?.[0]?.value,
onChange,
readOnly,
value: valueProp
});
const isEnabled = !(disabled || readOnly);
const wrapperProps: React.HTMLAttributes<HTMLDivElement> = useMemo(
() => ({
className,
style: { ...style, width }
}),
[className, style, width]
);
const DropdownButton = useMemo(
() => (
<StyledDropdownButton
as='div'
data-testid='select-button'
$disabled={disabled}
native={native}
tabIndex={-1}
variant={variant === 'flat' ? 'flat' : 'raised'}
>
<StyledDropdownIcon data-testid='select-icon' $disabled={disabled} />
</StyledDropdownButton>
),
[disabled, native, variant]
);
const Wrapper = useMemo(
() => (variant === 'flat' ? StyledFlatSelectWrapper : StyledSelectWrapper),
[variant]
);
return useMemo(
() => ({
isEnabled,
options,
value,
setValue,
wrapperProps,
DropdownButton,
Wrapper
}),
[DropdownButton, Wrapper, isEnabled, options, setValue, value, wrapperProps]
);
};