|
| 1 | +import React, { ChangeEvent } from "react"; |
| 2 | +import { StringUtils } from "andculturecode-javascript-core"; |
| 3 | +import { Icons } from "../constants/icons"; |
| 4 | +import { Icon } from "../icons/icon"; |
| 5 | + |
| 6 | +// ----------------------------------------------------------------------------------------- |
| 7 | +// #region Interfaces |
| 8 | +// ----------------------------------------------------------------------------------------- |
| 9 | + |
| 10 | +export interface SelectProps<T = any> { |
| 11 | + cssClassName?: string; |
| 12 | + id: string; |
| 13 | + onChange: (selectedOption?: SelectOption<T>) => void; |
| 14 | + name?: string; |
| 15 | + options: SelectOption<T>[]; |
| 16 | + value?: string; |
| 17 | +} |
| 18 | + |
| 19 | +export interface SelectOption<T = any> { |
| 20 | + data?: T; |
| 21 | + label: string; |
| 22 | + value: string; |
| 23 | +} |
| 24 | + |
| 25 | +// #endregion Interfaces |
| 26 | + |
| 27 | +// ----------------------------------------------------------------------------------------- |
| 28 | +// #region Component |
| 29 | +// ----------------------------------------------------------------------------------------- |
| 30 | + |
| 31 | +const Select: React.FC<SelectProps> = (props: SelectProps) => { |
| 32 | + const classNames = ["c-select"]; |
| 33 | + if (StringUtils.hasValue(props.cssClassName)) { |
| 34 | + classNames.push(props.cssClassName!); |
| 35 | + } |
| 36 | + |
| 37 | + const selectOptions = props.options.map((option) => ( |
| 38 | + <option key={option.value} value={option.value}> |
| 39 | + {option.label} |
| 40 | + </option> |
| 41 | + )); |
| 42 | + |
| 43 | + const handleChange = (e: ChangeEvent<HTMLSelectElement>) => { |
| 44 | + const option = props.options.find( |
| 45 | + (o: SelectOption) => o.value === e.target.value |
| 46 | + ); |
| 47 | + props.onChange(option); |
| 48 | + }; |
| 49 | + |
| 50 | + return ( |
| 51 | + <div className={classNames.join(" ")}> |
| 52 | + <select |
| 53 | + onChange={handleChange} |
| 54 | + value={props.value} |
| 55 | + name={props.name}> |
| 56 | + {selectOptions} |
| 57 | + </select> |
| 58 | + <Icon type={Icons.ChevronDown} /> |
| 59 | + </div> |
| 60 | + ); |
| 61 | +}; |
| 62 | + |
| 63 | +// #endregion Component |
| 64 | + |
| 65 | +// ----------------------------------------------------------------------------------------- |
| 66 | +// #region Exports |
| 67 | +// ----------------------------------------------------------------------------------------- |
| 68 | + |
| 69 | +export { Select }; |
| 70 | + |
| 71 | +// #endregion Exports |
0 commit comments