@trellixio/roaster-coffee
Version:
Beans' product component library
28 lines (27 loc) • 1.72 kB
JavaScript
import * as React from 'react';
import { classNames, useUid } from '@/utils';
function defaultOptionResolver(option) {
if (typeof option === 'string') {
return { label: option, value: option };
}
if ('id' in option && ('name' in option || 'title' in option)) {
return { label: option.name || option.title, value: option.id };
}
return option;
}
export const Select = React.forwardRef((props, ref) => {
const { label, data, helpText, prefix, prefixWidth = prefix ? 24 : 12, onChange, disabled, id, selectClassName, labelClassName, error, optionResolver = defaultOptionResolver, defaultValue, } = props;
const uid = useUid(id);
const normalizedData = data.map(optionResolver);
const options = normalizedData.map((item) => (React.createElement("option", { key: item.value, value: item.value, disabled: item.disabled }, item.label)));
const handleChange = (event) => {
onChange === null || onChange === void 0 ? void 0 : onChange(event.currentTarget.value);
};
return (React.createElement("label", { htmlFor: uid, className: classNames({ error }, labelClassName) },
React.createElement("p", null, label),
React.createElement("div", { className: classNames({ 'prefixed-input-container': prefix }) },
prefix && React.createElement("span", { className: "input-prefix" }, prefix),
React.createElement("select", { id: uid, ref: ref, className: classNames({ prefixed: prefix }, selectClassName), disabled: disabled, defaultValue: defaultValue, style: { paddingLeft: prefixWidth }, onChange: handleChange }, options)),
React.createElement("small", null, error || helpText)));
});
Select.displayName = 'Select';