-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSelect.js
More file actions
68 lines (62 loc) · 1.66 KB
/
Select.js
File metadata and controls
68 lines (62 loc) · 1.66 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
import React, {useState, useEffect} from 'react';
export default function Select({
id,
name,
value: initialValue,
options = [],
onChange,
className = '',
disabled = false,
placeholder = '',
multiple = false,
...props
}) {
const [selectedValue, setSelectedValue] = useState(
initialValue !== undefined ?
initialValue :
(multiple ? [] : ''),
);
useEffect(() => {
if (initialValue !== undefined) {
setSelectedValue(initialValue);
}
}, [initialValue, multiple]);
const handleChange = (event) => {
const newValue = multiple ?
Array.from(event.target.selectedOptions, (option) => option.value) :
event.target.value;
setSelectedValue(newValue);
// Call `onChange` from props, if exists
if (onChange) {
onChange(event);
}
};
return (
<select
id={id}
name={name}
value={selectedValue}
onChange={handleChange}
className={className}
disabled={disabled}
multiple={multiple}
{...props}
>
{placeholder && (
<option value="" disabled>
{placeholder}
</option>
)}
{options.map((option) => (
<option
key={option.value}
value={option.value}
disabled={option.disabled}
{...option.dataAttributes}
>
{option.label}
</option>
))}
</select>
);
}