Add Checkbox and CheckboxGroup component
[MAILPOET-2773]
This commit is contained in:
34
assets/js/src/common/form/checkbox/checkbox.tsx
Normal file
34
assets/js/src/common/form/checkbox/checkbox.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import React, { InputHTMLAttributes } from 'react';
|
||||
import classnames from 'classnames';
|
||||
|
||||
type Props = InputHTMLAttributes<HTMLInputElement> & {
|
||||
children?: React.ReactNode,
|
||||
isFullWidth?: boolean,
|
||||
onChange?: (boolean) => void,
|
||||
};
|
||||
|
||||
const Checkbox = ({
|
||||
children,
|
||||
isFullWidth,
|
||||
onChange,
|
||||
...attributes
|
||||
}: Props) => (
|
||||
<label
|
||||
className={
|
||||
classnames({
|
||||
'mailpoet-form-checkbox': true,
|
||||
'mailpoet-full-width': isFullWidth,
|
||||
})
|
||||
}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
{...attributes}
|
||||
/>
|
||||
<span className="mailpoet-form-checkbox-control" />
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
|
||||
export default Checkbox;
|
59
assets/js/src/common/form/checkbox/group.tsx
Normal file
59
assets/js/src/common/form/checkbox/group.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import React, { InputHTMLAttributes, useState } from 'react';
|
||||
import Checkbox from './checkbox';
|
||||
|
||||
type CheckboxValueType = string | string[] | number;
|
||||
|
||||
type CheckboxProps = InputHTMLAttributes<HTMLInputElement> & {
|
||||
label: string,
|
||||
}
|
||||
|
||||
type Props = {
|
||||
name: string,
|
||||
options: CheckboxProps[],
|
||||
defaultValue?: CheckboxValueType[]
|
||||
isFullWidth?: boolean,
|
||||
onChange?: (values: CheckboxValueType[]) => void,
|
||||
};
|
||||
|
||||
const CheckboxGroup = ({
|
||||
name,
|
||||
options,
|
||||
defaultValue,
|
||||
isFullWidth,
|
||||
onChange,
|
||||
}: Props) => {
|
||||
const [values, setValues] = useState(defaultValue || []);
|
||||
|
||||
const handleChange = (value: CheckboxValueType, isChecked: boolean) => {
|
||||
const index = values.indexOf(value);
|
||||
let newValues;
|
||||
if (isChecked && index === -1) {
|
||||
newValues = values.concat([value]);
|
||||
}
|
||||
if (!isChecked && index !== -1) {
|
||||
newValues = values.filter((val: CheckboxValueType) => val !== value);
|
||||
}
|
||||
setValues(newValues);
|
||||
onChange(newValues);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{options.map(({ label, value, ...attributes }: CheckboxProps) => (
|
||||
<Checkbox
|
||||
checked={values.indexOf(value) !== -1}
|
||||
key={label}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={(isChecked) => handleChange(value, isChecked)}
|
||||
isFullWidth={isFullWidth}
|
||||
{...attributes} // eslint-disable-line react/jsx-props-no-spreading
|
||||
>
|
||||
{label}
|
||||
</Checkbox>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CheckboxGroup;
|
Reference in New Issue
Block a user