116 lines
3.0 KiB
TypeScript
116 lines
3.0 KiB
TypeScript
// form
|
|
import { useFormContext, Controller } from 'react-hook-form';
|
|
// @mui
|
|
import { Checkbox, FormControlLabel, FormGroup, FormControlLabelProps } from '@mui/material';
|
|
|
|
// ----------------------------------------------------------------------
|
|
|
|
interface RHFCheckboxProps extends Omit<FormControlLabelProps, 'control'> {
|
|
name: string;
|
|
}
|
|
|
|
export function RHFCheckbox({ name, ...other }: RHFCheckboxProps) {
|
|
const { control } = useFormContext();
|
|
|
|
return (
|
|
<FormControlLabel
|
|
control={
|
|
<Controller
|
|
name={name}
|
|
control={control}
|
|
render={({ field }) => <Checkbox {...field} checked={field.value} />}
|
|
/>
|
|
}
|
|
{...other}
|
|
/>
|
|
);
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
|
|
interface RHFMultiCheckboxProps extends Omit<FormControlLabelProps, 'control' | 'label'> {
|
|
name: string;
|
|
options: string[];
|
|
}
|
|
|
|
export function RHFMultiCheckbox({ name, options, ...other }: RHFMultiCheckboxProps) {
|
|
const { control } = useFormContext();
|
|
|
|
return (
|
|
<Controller
|
|
name={name}
|
|
control={control}
|
|
render={({ field }) => {
|
|
const onSelected = (option: string) =>
|
|
field.value.includes(option)
|
|
? field.value.filter((value: string) => value !== option)
|
|
: [...field.value, option];
|
|
|
|
return (
|
|
<FormGroup>
|
|
{options.map((option) => (
|
|
<FormControlLabel
|
|
key={option}
|
|
control={
|
|
<Checkbox
|
|
checked={field.value.includes(option)}
|
|
onChange={() => field.onChange(onSelected(option))}
|
|
/>
|
|
}
|
|
label={option}
|
|
{...other}
|
|
/>
|
|
))}
|
|
</FormGroup>
|
|
);
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
|
|
// ----------------------------------------------------------------------
|
|
interface optionsCustomInterface {
|
|
value: string;
|
|
label: string;
|
|
}
|
|
interface RHFCustomMultiCheckboxProps {
|
|
name: string;
|
|
options: optionsCustomInterface[];
|
|
}
|
|
|
|
export function RHFCustomMultiCheckbox({ name, options, ...other }: RHFCustomMultiCheckboxProps) {
|
|
const { control } = useFormContext();
|
|
|
|
return (
|
|
<Controller
|
|
name={name}
|
|
control={control}
|
|
render={({ field }) => {
|
|
const onSelected = (option: optionsCustomInterface) =>
|
|
field.value.includes(option.value)
|
|
? field.value.filter((value: string) => value !== option.value)
|
|
: [...field.value, option.value];
|
|
|
|
return (
|
|
<FormGroup>
|
|
{options.map((option, index) => (
|
|
<FormControlLabel
|
|
key={index}
|
|
control={
|
|
<Checkbox
|
|
checked={field.value.includes(option.value)}
|
|
onChange={() => field.onChange(onSelected(option))}
|
|
/>
|
|
}
|
|
label={option.label}
|
|
{...other}
|
|
/>
|
|
))}
|
|
</FormGroup>
|
|
);
|
|
}}
|
|
/>
|
|
);
|
|
}
|