Skip to content

Commit fe5c703

Browse files
committed
Add common MultipleChoiceList component
1 parent c47309c commit fe5c703

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import React from 'react';
2+
import PropTypes from 'prop-types';
3+
import { composeValidators } from '@data-driven-forms/react-form-renderer';
4+
5+
import { formGroup } from './prop-types-templates';
6+
7+
const MultipleChoiceList = ({ validate, FieldProvider, Wrapper, Checkbox, ...props }) => (
8+
<FieldProvider
9+
{ ...props }
10+
validate={ composeValidators(props.validate || []) }
11+
render={ ({
12+
label,
13+
isRequired,
14+
helperText,
15+
meta,
16+
options,
17+
isDisabled,
18+
isReadOnly,
19+
description,
20+
...rest
21+
}) => {
22+
const { error, touched } = meta;
23+
const showError = touched && error;
24+
const groupValues = rest.input.value;
25+
return (
26+
<Wrapper
27+
showError={ showError }
28+
isRequired={ isRequired }
29+
label={ label }
30+
helperText={ helperText }
31+
meta={ meta }
32+
description={ description }
33+
rest={ rest }
34+
>
35+
{ options.map(option =>
36+
(<FieldProvider
37+
formOptions={ rest.formOptions }
38+
id={ `${rest.id}-${option.value}` }
39+
key={ option.value }
40+
{ ...option }
41+
name={ props.name }
42+
type="checkbox"
43+
render={ ({ input, meta, formOptions, componentType, ...rest }) => {
44+
const indexValue = groupValues.indexOf(input.value);
45+
return (
46+
<Checkbox
47+
aria-label={ option['aria-label'] || option.label }
48+
{ ...input }
49+
{ ...rest }
50+
isDisabled={ isDisabled || isReadOnly }
51+
onChange={ () => (indexValue === -1
52+
? input.onChange([ ...groupValues, input.value ])
53+
: input.onChange([ ...groupValues.slice(0, indexValue), ...groupValues.slice(indexValue + 1) ])) }
54+
label={ rest.label }
55+
/>
56+
);
57+
} }
58+
/>)) }
59+
</Wrapper>);
60+
} }
61+
/>
62+
);
63+
64+
MultipleChoiceList.propTypes = {
65+
validate: PropTypes.func,
66+
FieldProvider: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]),
67+
name: PropTypes.string.isRequired,
68+
Wrapper: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]),
69+
Checkbox: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]),
70+
};
71+
72+
export default MultipleChoiceList;
73+
74+
export const wrapperProps = {
75+
...formGroup,
76+
children: PropTypes.oneOfType([
77+
PropTypes.arrayOf(PropTypes.node),
78+
PropTypes.node,
79+
]).isRequired,
80+
};

0 commit comments

Comments
 (0)