misc_pterodactyl-panel/resources/scripts/components/elements/Checkbox.tsx

46 lines
1.4 KiB
TypeScript
Raw Normal View History

import React from 'react';
import { Field, FieldProps } from 'formik';
2020-07-04 23:26:07 +00:00
import Input from '@/components/elements/Input';
interface Props {
name: string;
value: string;
2020-07-11 22:37:59 +00:00
className?: string;
}
2020-07-04 23:26:07 +00:00
type OmitFields = 'ref' | 'name' | 'value' | 'type' | 'checked' | 'onClick' | 'onChange';
2020-07-04 23:26:07 +00:00
type InputProps = Omit<JSX.IntrinsicElements['input'], OmitFields>;
2020-07-11 22:37:59 +00:00
const Checkbox = ({ name, value, className, ...props }: Props & InputProps) => (
<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
{...field}
{...props}
2020-07-11 22:37:59 +00:00
className={className}
type={'checkbox'}
checked={(field.value || []).includes(value)}
onClick={() => form.setFieldTouched(field.name, true)}
onChange={(e) => {
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;