2022-12-21 21:27:50 +00:00
|
|
|
import type { FieldProps } from 'formik';
|
|
|
|
import { Field } from 'formik';
|
|
|
|
|
2020-07-04 23:26:07 +00:00
|
|
|
import Input from '@/components/elements/Input';
|
2020-02-23 04:07:56 +00:00
|
|
|
|
|
|
|
interface Props {
|
2022-12-21 21:27:50 +00:00
|
|
|
id: string;
|
2020-02-23 04:07:56 +00:00
|
|
|
name: string;
|
2022-12-21 21:27:50 +00:00
|
|
|
value?: string;
|
|
|
|
label?: string;
|
2020-07-11 22:37:59 +00:00
|
|
|
className?: string;
|
2020-02-23 04:07:56 +00:00
|
|
|
}
|
|
|
|
|
2020-07-04 23:26:07 +00:00
|
|
|
type OmitFields = 'ref' | 'name' | 'value' | 'type' | 'checked' | 'onClick' | 'onChange';
|
2020-02-23 04:07:56 +00:00
|
|
|
|
2020-07-04 23:26:07 +00:00
|
|
|
type InputProps = Omit<JSX.IntrinsicElements['input'], OmitFields>;
|
2020-02-23 04:07:56 +00:00
|
|
|
|
2020-07-11 22:37:59 +00:00
|
|
|
const Checkbox = ({ name, value, className, ...props }: Props & InputProps) => (
|
2020-02-23 04:07:56 +00:00
|
|
|
<Field name={name}>
|
|
|
|
{({ field, form }: FieldProps) => {
|
|
|
|
if (!Array.isArray(field.value)) {
|
|
|
|
console.error('Attempting to mount a checkbox using a field value that is not an array.');
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
2020-07-04 23:26:07 +00:00
|
|
|
<Input
|
2020-02-23 04:07:56 +00:00
|
|
|
{...field}
|
|
|
|
{...props}
|
2020-07-11 22:37:59 +00:00
|
|
|
className={className}
|
2020-02-23 04:07:56 +00:00
|
|
|
type={'checkbox'}
|
|
|
|
checked={(field.value || []).includes(value)}
|
|
|
|
onClick={() => form.setFieldTouched(field.name, true)}
|
2022-11-25 20:25:03 +00:00
|
|
|
onChange={e => {
|
2020-02-23 04:07:56 +00:00
|
|
|
const set = new Set(field.value);
|
|
|
|
set.has(value) ? set.delete(value) : set.add(value);
|
|
|
|
|
|
|
|
field.onChange(e);
|
|
|
|
form.setFieldValue(field.name, Array.from(set));
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}}
|
|
|
|
</Field>
|
|
|
|
);
|
|
|
|
|
|
|
|
export default Checkbox;
|