@nish1896/rhf-mui-components
Version:
A suite of 20+ production-ready react-hook-form components built with material-ui. Fully typed, tree-shakable, and optimized for enterprise-grade forms.
73 lines (72 loc) • 2.67 kB
JavaScript
"use client";
import { RHFMuiConfigContext } from "../../config/ConfigProvider.js";
import { fieldNameToLabel } from "../../utils/text-transform.js";
import { useFieldIds } from "../../utils/useFieldIds.js";
import FormHelperText from "../../common/FormHelperText.js";
import { Fragment, useContext } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { Controller } from "react-hook-form";
import FormControlLabel from "@mui/material/FormControlLabel";
import MuiCheckbox from "@mui/material/Checkbox";
//#region src/mui/checkbox/index.tsx
const RHFCheckbox = ({ fieldName, control, registerOptions, onValueChange, disabled: muiDisabled, label, formControlLabelProps, helperText, errorMessage, hideErrorMessage, formHelperTextProps, onBlur, slotProps: muiSlotProps, ...rest }) => {
const { fieldId, helperTextId, errorId } = useFieldIds(fieldName);
const { defaultFormControlLabelSx } = useContext(RHFMuiConfigContext);
const fieldLabel = label ?? fieldNameToLabel(fieldName);
const { sx, ...otherFormControlLabelProps } = formControlLabelProps ?? {};
const appliedFormControlLabelSx = {
...defaultFormControlLabelSx,
...sx
};
const { input: slotPropsInput, ...otherSlotProps } = muiSlotProps ?? {};
const isError = !!errorMessage;
const showHelperTextElement = !!helperText || isError && !hideErrorMessage;
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Controller, {
name: fieldName,
control,
rules: registerOptions,
render: ({ field: { name: rhfFieldName, value: rhfValue, onChange: rhfOnChange, onBlur: rhfOnBlur, ref: rhfRef } }) => {
return /* @__PURE__ */ jsx(FormControlLabel, {
control: /* @__PURE__ */ jsx(MuiCheckbox, {
id: fieldId,
name: rhfFieldName,
checked: Boolean(rhfValue),
disabled: muiDisabled,
"aria-describedby": showHelperTextElement ? isError ? errorId : helperTextId : void 0,
"aria-invalid": isError || void 0,
onChange: (event, checked) => {
rhfOnChange(checked);
onValueChange?.(checked, event);
},
onBlur: (blurEvent) => {
rhfOnBlur();
onBlur?.(blurEvent);
},
slotProps: {
...otherSlotProps,
input: {
...slotPropsInput,
ref: rhfRef
}
},
...rest
}),
label: fieldLabel,
sx: appliedFormControlLabelSx,
...otherFormControlLabelProps
});
}
}), /* @__PURE__ */ jsx(FormHelperText, {
error: isError,
errorMessage,
hideErrorMessage,
helperText,
showHelperTextElement,
formHelperTextProps: {
id: isError ? errorId : helperTextId,
...formHelperTextProps
}
})] });
};
//#endregion
export { RHFCheckbox as default };