RHF-MUI Components
NPM

RHFDatePicker

RHFDatePicker wraps the Material UI X Date Picker with label, error and helper-text handling, bound to React Hook Form through control.

Use a date picker when you need a calendar day without a time, such as a date of birth, a check-in date or an invoice due date. The stored value is a date object from your date library, so you can compare it with other dates, limit it with minDate and maxDate, or format it however your API expects.

Each picker comes in four variants, exported from the same module:

  • RHFDatePicker: responsive (renders the desktop UI on pointer devices, the mobile UI on touch).
  • RHFDesktopDatePicker: always renders the desktop (keyboard-first) UI.
  • RHFMobileDatePicker: always renders the mobile (modal) UI.
  • RHFStaticDatePicker: an always-visible inline picker with no text field.

Setup

All pickers read their date adapter from ConfigProvider. Wrap your app once and pass the adapter for your date library (Day.js, Luxon, date-fns or Moment).

import { ConfigProvider } from '@nish1896/rhf-mui-components/config';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';

<ConfigProvider dateAdapter={AdapterDayjs}>
  <App />
</ConfigProvider>

Without a dateAdapter, the pickers throw an error at render. This is the one required piece of setup.

Usage

import {
  RHFDatePicker,
  RHFDesktopDatePicker,
  RHFMobileDatePicker,
  RHFStaticDatePicker,
  type RHFDatePickerProps,
  type RHFDesktopDatePickerProps,
  type RHFMobileDatePickerProps,
  type RHFStaticDatePickerProps
} from '@nish1896/rhf-mui-components/mui-pickers/date';
import { type Dayjs } from 'dayjs';
import { useForm } from 'react-hook-form';

type FormValues = {
  dateOfBirth: Dayjs | null;
};

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

<form onSubmit={handleSubmit(values => console.log(values.dateOfBirth?.toISOString()))}>
  <RHFDatePicker
    fieldName="dateOfBirth"
    control={control}
    registerOptions={{ required: 'This field is required' }}
  />
</form>

value uses the date type of your date adapter, such as a Dayjs for AdapterDayjs. null clears the picker, so use null as the default value for an empty field.

By default, a change is stored in the form only when context.validationError is null. A half-typed or out-of-range entry is therefore not written to the form, and the field keeps its last valid value. Use customOnChange if you need to see every change, including invalid ones. onValueChange is called after a valid value is stored, and is not called when customOnChange is used.

Other variants

The other three variants take the same props. Use RHFDesktopDatePicker for the keyboard-first popover on every device, RHFMobileDatePicker for a modal dialog, and RHFStaticDatePicker for an always-visible picker without a text field.

<RHFMobileDatePicker
  fieldName="dateOfBirth"
  control={control}
/>

onAccept is passed through to MUI X and fires when the user finishes picking a value. The field is also marked as touched at that point, so mode: 'onTouched' validates once the user has picked a value.

Validation and date limits

Limit the selectable dates with the MUI X props minDate, maxDate, disablePast, disableFuture and shouldDisableDate. Disabled days can't be picked in the calendar. Typed dates outside the limits are not stored (see above), so pair the limits with rules in registerOptions to show a message:

import dayjs, { type Dayjs } from 'dayjs';

<RHFDatePicker
  fieldName="travelDate"
  control={control}
  minDate={dayjs()}
  maxDate={dayjs().add(1, 'year')}
  registerOptions={{
    required: 'Pick a travel date',
    validate: value =>
      !value || value.isBefore(dayjs().add(1, 'year')) || 'Travel date is too far ahead'
  }}
/>

To report the picker's own error, read context.validationError in customOnChange. It is one of 'invalidDate', 'minDate', 'maxDate', 'disablePast', 'disableFuture', 'shouldDisableDate', 'shouldDisableMonth' or 'shouldDisableYear', and null when the value is valid.

const { control, setError, clearErrors } = useForm<FormValues>();

<RHFDatePicker
  fieldName="travelDate"
  control={control}
  minDate={dayjs()}
  customOnChange={({ rhfOnChange, newValue, context }) => {
    if (context.validationError) {
      setError('travelDate', {
        type: context.validationError,
        message: 'Enter a valid date within the allowed range'
      });
      return;
    }
    clearErrors('travelDate');
    rhfOnChange(newValue);
  }}
/>

Customizing the input

format sets how the value is written in the field, using the tokens of your date library, such as 'DD/MM/YYYY' for Day.js. slotProps.textField is forwarded to the text field, as an object or a function, for props like size and fullWidth. The component controls the text field's id, error and ARIA attributes.

<RHFDatePicker
  fieldName="dateOfBirth"
  control={control}
  format="DD/MM/YYYY"
  slotProps={{ textField: { size: 'small', fullWidth: true } }}
/>

Labels, errors and disabling

showLabelAboveFormField, hideLabel and formLabelProps control the label, helperText, renderError and hideErrorMessage control the message below the field, and disabled (or a form-level disabled in useForm) disables it. These work as described in RHFTextField.

Info

RHFStaticDatePicker renders inline with no text field, so two props behave slightly differently: fieldName only derives the generated ids and default label (no name attribute, since there is no input), and showLabelAboveFormField defaults to false, which means no visible label renders at all (the accessible name is still applied).

Handling value changes

By default a change is stored only when context.validationError is null. onValueChange runs after a valid value has been stored. It receives { newValue, context }:

<RHFDatePicker
  fieldName="dateOfBirth"
  control={control}
  onValueChange={({ newValue, context }) => {
    console.log(newValue?.format('YYYY-MM-DD'))
  }}
/>

Use customOnChange when you need to see every change, including invalid ones, or to change what gets stored. It replaces the default handling, so you must call rhfOnChange yourself with the value to store. It receives { rhfOnChange, newValue, context }. onValueChange is not called when customOnChange is used.

<RHFDatePicker
  fieldName="dateOfBirth"
  control={control}
  customOnChange={({ rhfOnChange, newValue, context }) => {
    if (context.validationError === null) {
      rhfOnChange(newValue?.startOf('day') ?? null);
    }
  }}
/>

Examples

API

RHFDatePickerProps extends DatePickerProps 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.
requiredboolean
Indicates that the field is mandatory by adding an asterisk symbol (*) to the formLabel. This visual cue helps users quickly identify required fields in the form.
customOnChange({ rhfOnChange, newValue, context }) => void
Custom change handler that overrides the default date value update behavior. Receives rhfOnChange, the updated date value, and the MUI picker change context. When provided, you must call rhfOnChange manually to update the form value.
onValueChange({ newValue, context }) => void
Optional callback fired when the selected date changes and the picker value is valid. Receives the updated date value and the MUI picker change context.
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.
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.