@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
33 lines (32 loc) • 2.59 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Controller } from 'react-hook-form';
import FormControl from '@mui/material/FormControl';
import NativeSelect from '@mui/material/NativeSelect';
import { FormLabel, FormHelperText } from '../../mui/common';
import { fieldNameToLabel, isKeyValueOption, validateArray } from '../../utils';
const RHFNativeSelect = ({ fieldName, control, registerOptions, options, labelKey, valueKey, onValueChange, defaultOptionText, showLabelAboveFormField, formLabelProps, label, required, helperText, errorMessage, hideErrorMessage, formHelperTextProps, sx, ...otherNativeSelectProps }) => {
validateArray('RHFNativeSelect', options, labelKey, valueKey);
const fieldLabel = label ?? fieldNameToLabel(fieldName);
const isError = Boolean(errorMessage);
const blankOptionText = defaultOptionText ?? `Select ${fieldName}`;
return (_jsxs(FormControl, { fullWidth: true, 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: { onChange, value, ...rest } }) => (_jsxs(NativeSelect, { ...otherNativeSelectProps, ...rest, value: value ?? '', inputProps: {
name: fieldName,
id: fieldName
}, onChange: event => {
onChange(event.target.value);
if (onValueChange) {
onValueChange(event.target.value, event);
}
}, sx: {
...sx,
'&.MuiNativeSelect-root': {
margin: 0,
}
}, children: [_jsx("option", { value: "", children: blankOptionText }), options.map(option => {
const isObject = isKeyValueOption(option, labelKey, valueKey);
const opnValue = isObject ? `${option[valueKey ?? '']}` : option;
const opnLabel = isObject ? `${option[labelKey ?? '']}` : option;
return (_jsx("option", { value: opnValue, children: opnLabel }, opnValue));
})] })) }), _jsx(FormHelperText, { error: isError, errorMessage: errorMessage, hideErrorMessage: hideErrorMessage, helperText: helperText, formHelperTextProps: formHelperTextProps })] }));
};
export default RHFNativeSelect;