RHF-MUI Components
NPM

RHFSelect

RHFSelect wraps the Material UI Select with label, error and helper-text handling, bound to React Hook Form through control. It supports single or multiple selection and accepts both arrays and arrays of objects, so options with differing labels and values need no custom logic.

Tip

If the number of options exceeds 20, consider using RHFAutocomplete or RHFMultiAutocomplete for better searchability, improved keyboard navigation, and overall performance.

Usage

import RHFSelect, { RHFSelectProps } from '@nish1896/rhf-mui-components/mui/select';
import { useForm } from 'react-hook-form';

type FormValues = {
  role: string;
};

const { control, handleSubmit } = useForm<FormValues>({
  defaultValues: { role: '' }
});

<form onSubmit={handleSubmit(values => console.log(values))}>
  <RHFSelect
    fieldName="role"
    control={control}
    options={['Admin', 'Editor', 'Viewer']}
    registerOptions={{ required: 'Please select a role' }}
  />
</form>

With primitive options, the stored value has the same type as the options, so a string option gives a string and a number option gives a number. onValueChange receives { newValue, event, child }: the normalized value, the Material UI change event, and the selected option element.

undefined, null and '' all mean no selection.

Selecting multiple values

Set multiple to store an array. The values are kept in the order they were selected, and keep the type of the options. Use [] as the default value.

type FormValues = {
  roles: string[];
};

const { control } = useForm<FormValues>({
  defaultValues: { roles: [] }
});

<RHFSelect
  fieldName="roles"
  control={control}
  options={['Admin', 'Editor', 'Viewer']}
  multiple
  registerOptions={{
    validate: value => value.length > 0 || 'Select at least one role'
  }}
/>

The closed field shows the labels of the selected options joined with , . Use renderValue to display it differently, as described in Custom selected value.

With an array of objects

When options is an array of objects, both labelKey and valueKey are required.

  • labelKey: the property used as each option's visible label.
  • valueKey: the property used as each option's value.

The stored value has the type of the valueKey property. With multiple, it is an array of those values.

<RHFSelect
  fieldName="country"
  control={control}
  options={[
    { code: 'AUS', country: 'Australia' },
    { code: 'IN', country: 'India' },
    { code: 'UAE', country: 'United Arab Emirates' }
  ]}
  labelKey="country"
  valueKey="code"
/>
Warning

When using an array of objects for options, both labelKey and valueKey are required. If either is missing, an error will be thrown.

Default option & placeholder

Two props help when nothing is selected yet. showDefaultOption adds a first menu item with the value '', labelled with defaultOptionText, which defaults to "Select" followed by the label generated from fieldName, such as Select Role. Choosing it clears the selection. It is disabled when the field is required, so it can't be picked once a real option is chosen.

placeholder is text shown inside the closed field while nothing is selected. Unlike the default option it isn't a menu item, it is shown faded, and the inline label is not rendered while it is shown.

<RHFSelect
  fieldName="role"
  control={control}
  options={['Admin', 'Editor', 'Viewer']}
  showDefaultOption
  defaultOptionText="No role"
/>

<RHFSelect
  fieldName="plan"
  control={control}
  options={['Free', 'Pro', 'Team']}
  placeholder="Choose a plan"
/>

Customizing individual options

renderOptionLabel replaces the content of each menu item. It receives the option and a state object with disabled and selected, so the label can react to either. getOptionDisabled receives an option and returns true to disable it.

<RHFSelect
  fieldName="product"
  control={control}
  options={[
    { id: 1, name: 'Keyboard', stock: 12 },
    { id: 2, name: 'Monitor', stock: 0 },
    { id: 3, name: 'Mouse', stock: 4 }
  ]}
  labelKey="name"
  valueKey="id"
  renderOptionLabel={(option, { disabled, selected }) => (
    <span
      style={{
        opacity: disabled ? 0.5 : 1,
        fontWeight: selected ? 700 : 400
      }}
    >
      {option.name} ({option.stock} in stock)
    </span>
  )}
  getOptionDisabled={option => option.stock === 0}
/>

Custom selected value

renderValue changes what the closed field displays, while renderOptionLabel only changes the menu items. It receives the normalized value, which is an array when multiple is set.

<RHFSelect
  fieldName="tags"
  control={control}
  options={['Bug', 'Feature', 'Docs', 'Chore']}
  multiple
  renderValue={selected =>
    selected.length ? `${selected.length} selected` : ''
  }
/>

Styling the options

menuItemProps is forwarded to every MenuItem, including the default option, which is handy for a shared dense, divider or sx. inputLabelProps is forwarded to the InputLabel shown inside the field's outline. It has no effect when the field uses a label above (showLabelAboveFormField), hideLabel, or a placeholder with no value selected.

<RHFSelect
  fieldName="role"
  control={control}
  options={['Admin', 'Editor', 'Viewer']}
  menuItemProps={{ dense: true, sx: { fontSize: 14 } }}
  inputLabelProps={{ sx: { fontWeight: 600 } }}
/>

Handling value changes

onValueChange runs after the new value has been stored in the form. It receives { newValue, event, child }: the normalized value, the Material UI change event, and the selected option element. Use it for side effects, such as loading dependent data:

<RHFSelect
  fieldName="country"
  control={control}
  options={['India', 'Germany', 'Canada']}
  onValueChange={({ newValue, event, child }) => fetchCities(newValue)}
/>

Use customOnChange when you need to change what gets stored. It replaces the default handling, so you must call rhfOnChange yourself with the value to store. This example limits a multiple select to three values: onValueChange is not called when customOnChange is used.

<RHFSelect
  fieldName="roles"
  control={control}
  options={['Admin', 'Editor', 'Viewer', 'Guest']}
  multiple
  customOnChange={({ rhfOnChange, newValue, event, child }) => {
    if (newValue.length <= 3) {
      rhfOnChange(newValue);
    }
  }}
/>

The label, helper text and error props work as described in RHFTextField.

Wrapping the component

You can extend or reuse the RHFSelect component by creating your own wrapper component.

/**
 * The below code snippet illustrates how to create a reusable styled Select
 * component using RHFSelect, which can be used throughout the application.
 *
 * `multiple` is left in the prop surface (not `Omit`'d) so its generic
 * `Multiple` type param is inferred per call site from the literal passed —
 * same as `RHFSelect` itself. Omitting `multiple` from the props type would
 * pin `Multiple` to its default and make passing `multiple={false}` a type
 * error.
 *
 * A similar approach can be taken to create reusable styled components for:
 * - RHFNativeSelect
 * - RHFCheckboxGroup
 * - RHFRadioGroup
 */

import { type FieldValues } from 'react-hook-form';
import { Poppins } from 'next/font/google';
import RHFSelect, {
  type RHFSelectProps
} from '@nish1896/rhf-mui-components/mui/select';
import type { StrNumObjOption } from '@nish1896/rhf-mui-components/types';

const poppins = Poppins({
  subsets: ['latin'],
  style: 'italic',
  weight: ['100', '200', '300', '400', '500', '600', '700', '800', '900']
});

type StyledSelectProps<
  T extends FieldValues,
  Option extends StrNumObjOption = StrNumObjOption,
  LabelKey extends Extract<keyof Option, string> = Extract<keyof Option, string>,
  ValueKey extends Extract<keyof Option, string> = Extract<keyof Option, string>,
  Multiple extends boolean = true
> = Omit<
  RHFSelectProps<T, Option, LabelKey, ValueKey, Multiple>,
  'showLabelAboveFormField'
>;

const StyledSelect = <
  T extends FieldValues,
  Option extends StrNumObjOption = StrNumObjOption,
  LabelKey extends Extract<keyof Option, string> = Extract<keyof Option, string>,
  ValueKey extends Extract<keyof Option, string> = Extract<keyof Option, string>,
  Multiple extends boolean = true
>({
  formLabelProps,
  ...rest
}: StyledSelectProps<T, Option, LabelKey, ValueKey, Multiple>) => {

  return (
    <RHFSelect
      formLabelProps={{
        ...formLabelProps,
        sx: {
          fontFamily: poppins.style.fontFamily,
          fontWeight: 400,
          ...formLabelProps?.sx
        }
      }}
      showLabelAboveFormField
      {...rest}
    />
  );
};

export default StyledSelect;

Examples

API

The RHFSelectProps interface extends SelectProps and accepts the following additional props. Props marked with * are required.

NameTypeDescription
fieldName*string
Name of the field registered with React Hook Form. This prop is required for all components.
control*UseFormControl
The control option yielded on calling the useForm hook.
registerOptionsRegisterOptions
React Hook Form validation rules. Useful when not using a schema validation library such as Yup or Joi.
options*string[] / number[] / object[]
An array with string, numeric or object values. Make sure to pass labelKey and valueKey when options is an array of objects.
labelKeystring
Property name used as the visible label for each option.
Required when options is an array of objects.
valueKeystring
Property name used as the stored value for each option.
Required when options is an array of objects.
multipleboolean
Allows multiple values to be selected.
customOnChange({ rhfOnChange, newValue, event, child }) => void
Override the default onChange behavior of the select component. You must pass the updated newValue to the rhfOnChange function to update the field value.
onValueChange({ newValue, event, child }) => void
An optional callback function when an option is selected. The latest value can be obtained from newValue argument.
renderOptionLabel(option) => ReactNode
Custom renderer for option labels. When not provided, the label is derived from the option value or the property specified by labelKey.
Option state param added in v4.2.0
getOptionDisabled(option) => boolean
Function used to determine whether an option should be disabled. Return true to disable the option and prevent it from being selected.
menuItemPropsMenuItemProps
Props forwarded to each internal MUI MenuItem, applied to every rendered option.
Added in v4.3.
showDefaultOptionboolean
Displays a default option with an empty value ('') at the top of the dropdown. The displayed text can be customized using defaultOptionText.
defaultOptionTextstring
Custom text to replace the default text when showDefaultOption is true for RHFSelect or RHFNativeSelect.
labelReactNode
The text to render in the FormLabel component. By default, the value of fieldName is transformed (e.g., "firstName" to "First Name") using the fieldNameToLabel function.
inputLabelPropsInputLabelProps
Props forwarded to the InputLabel — the inline label shown inside the field's outline.
Added in v4.3.
showLabelAboveFormFieldboolean
Render form label above the form field in FormLabel component.
formLabelPropsFormLabelProps
FormLabelProps to customise FormLabel component for a field. Multiple fields can be configured using the ConfigProvider component.
hideLabelboolean
Hides the FormLabel component if you don’t want to display the default form label component or prefer to render a fully custom label instead.
renderError(error: FieldError) => ReactNode
Custom renderer for the React Hook Form field error. Receives the current field error and returns the content to display, such as error.message or a custom React element in the HelperText component.
Added in v4.1.0.
hideErrorMessageboolean
A flag to prevent replacement of helper text of a field by the errorMessage when the validation is triggered.
helperTextReactNode
The content to display within the FormHelperText component below the field. If the field validation fails, this content will be overridden by the corresponding error message.
formHelperTextPropsFormHelperTextProps
FormHelperTextProps to customise FormHelperText component for a field. Multiple fields can be configured using the ConfigProvider component.
customIds{ field, label, helperText, error }
Overrides the default field, label, helper text, and error IDs used for accessibility.

Source Code

View the full implementation of this component on GitHub.