From 5e91d955f8617e893c0fae5efdd45960f1fc8ad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mikael=20J=C3=A4rvinen?= Date: Wed, 23 Aug 2023 11:08:34 +0300 Subject: [PATCH] fix: Fix support for checkbox in select --- src/components/Select.tsx | 72 +++++++++++++++++++------------ stories/Inputs/Select.stories.tsx | 9 ++-- 2 files changed, 50 insertions(+), 31 deletions(-) diff --git a/src/components/Select.tsx b/src/components/Select.tsx index b3e0cae7e..2f449b8fe 100644 --- a/src/components/Select.tsx +++ b/src/components/Select.tsx @@ -3,6 +3,8 @@ import TextField, { TextFieldProps } from './TextField'; import Autocomplete, { AutocompleteProps, OptionsType } from './Autocomplete'; import { forwardRef, Ref } from 'react'; import Typography from './Typography'; +import Checkbox from './Checkbox'; +import React from 'react'; type CommonProps = { options?: AutocompleteProps['options']; @@ -34,7 +36,7 @@ const Select = ( ...props }: SelectProps, ref: Ref -): JSX.Element => { +): React.JSX.Element => { if (multiple) { return ( ); } + + const selectProps = 'SelectProps' in props ? props.SelectProps : {}; + const isMultiple = 'SelectProps' in props && props.SelectProps?.multiple; + return ( options.find((o) => o.id == value)?.value, + renderValue: (value) => { + if (value instanceof Array) return value.map((v) => options.find((o) => o.id == v)?.value).join(', '); + + return options.find((o) => o.id == value)?.value; + }, + ...selectProps, }} - inputProps={{ 'data-testid': testid }} - {...(props as SingleSelectProps)} - ref={ref as Ref} > - {options.map(({ id, value: label, description, disabled }) => ( - - {label} - {description && ( - - {description} - - )} - - ))} + {options.map(({ id, value: label, description, disabled }) => { + const isChecked = isMultiple && (props.value as Array).map((i) => i.toString()).indexOf(id.toString()) > -1; + + return ( + + {checkbox && ()} + {label} + {description && ( + + {description} + + )} + + )})} ); }; diff --git a/stories/Inputs/Select.stories.tsx b/stories/Inputs/Select.stories.tsx index de3d2b04b..0b41eb6d5 100644 --- a/stories/Inputs/Select.stories.tsx +++ b/stories/Inputs/Select.stories.tsx @@ -30,7 +30,8 @@ export default { } as Meta; const SelectTemplate: StoryFn = (args: SelectProps) => { - const [selectValue, setSelectValue] = useState('0'); + const isMultiple = Boolean('SelectProps' in args && args.SelectProps?.multiple); + const [selectValue, setSelectValue] = useState | string | number>(isMultiple ? [0] : 0); args.value = selectValue; args.onChange = (e: ChangeEvent) => setSelectValue(e.target.value); @@ -126,11 +127,13 @@ MultipleSelect.args = { fullWidth: true, }; -export const MultipleSelectCheckbox = MultiSelectTemplate.bind({}); +export const MultipleSelectCheckbox = SelectTemplate.bind({}); MultipleSelectCheckbox.args = { - multiple: true, placeholder: 'Select', fullWidth: true, + SelectProps: { + multiple: true, + }, checkbox: true, };