UNPKG

react-form-in-second

Version:
97 lines (63 loc) 1.53 kB
const OptionItem = ({value, label, children}) => { if (Array.isArray(children) && children.length) { return ( <optgroup label={label}> { children.map(item => <OptionItem {...item} key={item.value} />) } </optgroup> ) } return <option value={value}>{label}</option> } const Select = (props) => { const fields = [ 'name', 'value', 'disabled', 'multiple', 'placeholder', 'required', ] const onChangeVal = evt => { let { name, value } = evt.target , { onChange, multiple } = props if (multiple) { value = []; for (let opt of evt.target.options) { if (opt.selected) value.push(opt.value) } } if (typeof onChange === 'function') onChange(name, value) } const attrs = { className: 'form-control ' + (props.inputClassName || ' '), onChange: onChangeVal } fields.forEach(field => { attrs[field] = props[field] }) if (props.multiple && !Array.isArray(attrs.value)) { attrs.value = [] }; const renderOptions = () => { const { options } = props return Array.isArray(options) &&options.map(item => <OptionItem {...item} key={item.value} />) } return ( <select {...attrs}> {renderOptions()} </select> ) } const SelectWrapper = (props) => { const { className, label, error, children } = props return ( <div className={`form-group ${className || ''}`}> <label>{label}</label> <Select {...props}/> {children} {error && <span className="error">{error}</span>} </div> ) } export default SelectWrapper