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