@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
29 lines (28 loc) • 1.92 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 MuiCheckbox from '@mui/material/Checkbox';
import { RHFMuiConfigContext } from '../../config/ConfigProvider';
import { FormHelperText } from '../../mui/common';
import { fieldNameToLabel } from '../../utils';
const RHFCheckbox = ({ fieldName, control, registerOptions, onValueChange, label, formControlLabelProps, helperText, errorMessage, hideErrorMessage, formHelperTextProps, ...rest }) => {
const { defaultFormControlLabelSx } = useContext(RHFMuiConfigContext);
const fieldLabel = label ?? fieldNameToLabel(fieldName);
const isError = Boolean(errorMessage);
const { sx, ...otherFormControlLabelProps } = formControlLabelProps ?? {};
const appliedFormControlLabelSx = {
...defaultFormControlLabelSx,
...sx,
};
return (_jsxs(Fragment, { children: [_jsx(Controller, { name: fieldName, control: control, rules: registerOptions, render: ({ field }) => {
const { value, onChange, ...otherFieldParams } = field;
return (_jsx(FormControlLabel, { control: _jsx(MuiCheckbox, { ...otherFieldParams, ...rest, checked: Boolean(value), onChange: (event, checked) => {
onChange(checked);
if (onValueChange) {
onValueChange(checked, event);
}
} }), label: fieldLabel, sx: appliedFormControlLabelSx, ...otherFormControlLabelProps }));
} }), _jsx(FormHelperText, { error: isError, errorMessage: errorMessage, hideErrorMessage: hideErrorMessage, helperText: helperText, formHelperTextProps: formHelperTextProps })] }));
};
export default RHFCheckbox;