@nish1896/rhf-mui-components
Version:
A suite of 20+ reusable Material UI components for React Hook Form to minimize your time and effort in creating and styling forms
43 lines (42 loc) • 3.15 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useContext, Fragment } from 'react';
import { Controller } from 'react-hook-form';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { RHFMuiConfigContext } from '../../config/ConfigProvider';
import { FormControl, FormLabel, FormHelperText } from '../../mui/common';
import { fieldNameToLabel, validateArray, isKeyValueOption } from '../../utils';
const RHFCheckboxGroup = ({ fieldName, control, registerOptions, options, labelKey, valueKey, onValueChange, disabled, label, showLabelAboveFormField, formLabelProps, checkboxProps, formControlLabelProps, required, helperText, errorMessage, hideErrorMessage, formHelperTextProps }) => {
validateArray('RHFCheckboxGroup', options, labelKey, valueKey);
const { defaultFormControlLabelSx } = useContext(RHFMuiConfigContext);
const fieldLabel = label ?? fieldNameToLabel(fieldName);
const isError = Boolean(errorMessage);
const { sx, ...otherFormControlLabelProps } = formControlLabelProps ?? {};
const appliedFormControlLabelSx = {
...defaultFormControlLabelSx,
...sx
};
return (_jsxs(FormControl, { error: isError, children: [_jsx(FormLabel, { label: fieldLabel, isVisible: showLabelAboveFormField ?? true, required: required, error: isError, formLabelProps: formLabelProps }), _jsx(Controller, { name: fieldName, control: control, rules: registerOptions, render: ({ field }) => {
const { value, onChange } = field;
const handleChange = (event, checked) => {
const newValue = checked
? [...(value ?? []), event.target.value]
: value.filter((v) => v !== event.target.value);
onChange(newValue);
if (onValueChange) {
onValueChange(event.target.value, newValue, event);
}
};
return (_jsx(Fragment, { children: options.map((option, idx) => {
const isObject = isKeyValueOption(option, labelKey, valueKey);
const opnValue = isObject
? `${option[valueKey ?? '']}`
: option;
const opnLabel = isObject
? `${option[labelKey ?? '']}`
: option;
return (_jsx(FormControlLabel, { control: _jsx(Checkbox, { ...checkboxProps, name: fieldName, value: opnValue, checked: (value ?? []).includes(opnValue), onChange: e => handleChange(e, e.target.checked) }), label: `${opnLabel}`, sx: appliedFormControlLabelSx, disabled: disabled, ...otherFormControlLabelProps }, idx));
}) }));
} }), _jsx(FormHelperText, { error: isError, errorMessage: errorMessage, hideErrorMessage: hideErrorMessage, helperText: helperText, formHelperTextProps: formHelperTextProps })] }));
};
export default RHFCheckboxGroup;