Skip to content

Commit

Permalink
fix(Select): handle multiple value
Browse files Browse the repository at this point in the history
  • Loading branch information
zouxuoz committed Oct 29, 2018
1 parent 3b269cb commit 7eef95b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 29 deletions.
75 changes: 46 additions & 29 deletions src/atoms/dataEntry/SelectField/SelectField.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,35 +29,52 @@ const theme = createTheme(name, {
},
});

function SelectField({
options,
placeholder,
label,
stretch,
input = {},
meta = {},
...rest
}: SelectFieldProps) {
const { name, value, onChange } = input;

const hasError = formUtils.hasError(meta);

const selectedOption = options.find((option) => option.value === value);

return (
<FormField label={ label } stretch={ stretch } input={ input } meta={ meta }>
<Select
{ ...rest }
name={ name }
onChange={ (selectedOption) => onChange(selectedOption ? selectedOption.value : null) }
placeholder={ placeholder }
value={ selectedOption }
options={ options }
stretch={ stretch }
hasError={ hasError }
/>
</FormField>
);
class SelectField extends React.Component<SelectFieldProps> {
onChange = (selectedOption) => {
const value = Array.isArray(selectedOption)
? selectedOption.map(({ value }) => value)
: (selectedOption.value || null);

this.props.input.onChange(value);
};

collectFormFieldProps() {
const { meta, input, stretch, label } = this.props;

return { meta, input, stretch, label };
}

collectSelectProps() {
const { input, meta, placeholder, options, stretch } = this.props;

const hasError = formUtils.hasError(meta);

const value = Array.isArray(input.value)
? options.filter((option) => input.value.indexOf(option.value) !== -1)
: options.find((option) => option.value === input.value);

return {
...this.props,
name: input.name,
value,
hasError,
placeholder,
options,
stretch,
onChange: this.onChange,
};
}

render() {
const collectedFormFieldProps = this.collectFormFieldProps();
const collectedSelectProps = this.collectSelectProps();

return (
<FormField { ...collectedFormFieldProps }>
<Select { ...collectedSelectProps } />
</FormField>
);
}
}

export { SelectField, theme };
1 change: 1 addition & 0 deletions src/atoms/dataEntry/SelectField/SelectField.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default (asStory) => {
<SelectField
label="Select Label"
input={{ name: 'input', onChange: () => null, value: OPTIONS[0].value }}
meta={{}}
placeholder="Select an option"
options={ OPTIONS }
stretch
Expand Down

0 comments on commit 7eef95b

Please sign in to comment.