Skip to Content
Piplup
@piplup/rhf-adaptersmui-x-date-pickersHooks

useMuiXTimePickerAdapter

Returns adapter props for MUI X TimePicker with React Hook Form, including minTime, maxTime, minutesStep and shouldDisableTime.

useMuiXTimePickerAdapter connects a field to React Hook Form and returns props you spread onto MUI X's TimePicker. It's what MuiXTimePickerElement uses internally.

Use the element for most forms. Reach for the hook when you want your own time field component, for example one that always enforces opening hours or a minute step, or one that shares form wiring across several pickers. This page describes the time validation that all time hooks share.

Import

import { useMuiXTimePickerAdapter } from '@piplup/rhf-adapters/mui-x-date-pickers';

Usage

This ShiftStartField only accepts times between 08:00 and 18:00 on the quarter hour, with its own messages. Submit it empty, or type 07:30 or 09:10, to see the validation.

hh:mm

08:00 to 18:00, every 15 minutes

'use client';import Stack from '@mui/material/Stack';import { LocalizationProvider, TimePicker } from '@mui/x-date-pickers';import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';import { MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useMuiXTimePickerAdapter } from '@piplup/rhf-adapters/mui-x-date-pickers';import dayjs from 'dayjs';import { useForm } from 'react-hook-form';import type { Dayjs } from 'dayjs';import type { Control } from 'react-hook-form';type FormValues = { shiftStart: Dayjs | null };// Only the time of day is compared, so the date part of these values does not matter.const opensAt = dayjs().hour(8).minute(0);const closesAt = dayjs().hour(18).minute(0);// Shifts start between 08:00 and 18:00, on the quarter hour.function ShiftStartField({ control }: { control: Control<FormValues> }) {  const adapter = useMuiXTimePickerAdapter<Dayjs, FormValues, 'shiftStart', HTMLDivElement>({    composeHelperText: true,    control,    maxTime: closesAt,    messages: {      maxTime: 'The last shift starts at 18:00',      minTime: 'We open at 08:00',      minutesStep: 'Use a quarter hour (:00, :15, :30 or :45)',      required: 'Pick a start time',    },    minTime: opensAt,    minutesStep: 15,    name: 'shiftStart',    required: true,    slotProps: {      textField: { helperText: '08:00 to 18:00, every 15 minutes' },    },  });  return <TimePicker ampm={false} label="Shift start" {...adapter} />;}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { shiftStart: null },  });  return (    <LocalizationProvider dateAdapter={AdapterDayjs}>      <form        onSubmit={handleSubmit((values) => alert(values.shiftStart?.format('HH:mm')))}        noValidate      >        <Stack direction="column" spacing={2}>          <ShiftStartField control={control} />          <div>            <MuiButtonElement control={control} type="submit" variant="contained">              Save shift            </MuiButtonElement>          </div>        </Stack>      </form>    </LocalizationProvider>  );}

The hook must run inside a LocalizationProvider, because it reads the date adapter to validate values.

How it works

Value. The field value is passed to the picker as-is, with undefined converted to null so the picker stays controlled. Pass transform if your form stores something other than a date object.

Validation props reach the picker too. minTime, maxTime, minutesStep, shouldDisableTime, disablePast, disableFuture and disableIgnoringDatePartForTimeValidation are returned by the hook, so the picker greys out the same times that validation rejects. disablePast and disableFuture default to false.

Validation. The hook runs MUI X's validateTime on every non-empty value. Empty values pass; add required to reject them. Checks run in this order and only the first failure is reported:

OrderKeyFails whenDefault message
1invalidDatethe value is not a valid date, e.g. a half-typed timeDate is not a valid date
2minTimethe time is before minTimeTime is earlier than the minimum allowed time
3maxTimethe time is after maxTimeTime is later than the maximum allowed time
4disableFuturethe value is after nowFuture date is not allowed
5disablePastthe value is before nowPast date is not allowed
6shouldDisableTime-hoursshouldDisableTime(value, "hours") returns trueHour is disabled
7shouldDisableTime-minutesshouldDisableTime(value, "minutes") returns trueMinute is disabled
8shouldDisableTime-secondsshouldDisableTime(value, "seconds") returns trueSecond is disabled
9minutesStepthe minutes are not a multiple of minutesStepMinute step is not valid

required uses "Please fill out this field." The messages above are the exact default text.

Time of day only. minTime and maxTime compare only the time of day, so the date part of the values you pass is ignored. Set disableIgnoringDatePartForTimeValidation to compare full date-times instead. disablePast and disableFuture always compare against the current date and time.

Timezone. Validation uses the timezone prop when given, otherwise the timezone of the value.

Custom messages. Pass any key from the table in messages, as a string or a function. A function receives the value, and for minTime, maxTime and minutesStep also the limit, for example (value, minTime) => "Open from " + minTime.format("HH:mm"). invalidDate is typed as a function only, so write it as invalidDate: () => "Enter a valid time".

Errors and helper text. The returned slotProps.textField sets error and helperText from the field state and merges your own slotProps.textField (an object or a function). The hook has no top-level helperText prop; put your hint in slotProps.textField.helperText. With composeHelperText: true an error message replaces that hint while the field is invalid. Without it, only the error state is applied.

Blur and touched. The returned slotProps.textField calls React Hook Form's onBlur, so typing a time and tabbing away marks the field as touched. The returned onClose also calls onBlur and then your own onClose, so closing the picker counts as a blur too.

Your own rules.validate. A validate function or object in rules runs next to the built-in time validation, not instead of it.

Refs. React Hook Form's ref, merged with your inputRef, is returned as inputRef, so setFocus and focus-on-error move focus to the input. The hook's second argument becomes ref on the picker root.

Variants

The other time hooks use the same validation and messages. They differ in where errors can render and how a field becomes touched:

HookText fieldErrors shown byTouched on
useMuiXDesktopTimePickerAdapteryesslotProps.textFieldinput blur or picker close
useMuiXMobileTimePickerAdapteryesslotProps.textFieldinput blur or dialog close
useMuiXStaticTimePickerAdapternoyou render themnever
useMuiXTimeFieldAdapteryes, no popuperror / helperText propsinput blur
useMuiXTimeClockAdapternoyou render themblur inside the clock
useMuiXDigitalClockAdapternoyou render themblur inside the clock
useMuiXMultiSectionDigitalClockAdapternoyou render themblur inside the clock

Desktop, mobile and static versions

TimePicker picks its layout from the device: a popover when the pointer is precise, such as a mouse, and a dialog on touch screens. MUI X also has three versions with a fixed layout, and each has a hook, compared in the Variants table above.

The desktop and mobile hooks call useMuiXTimePickerAdapter with the same props and return its result unchanged, so everything above applies to them. The static hook validates the same way, but returns the error for you to render.

DesktopTimePicker

useMuiXDesktopTimePickerAdapter returns props for DesktopTimePicker. Use it when you build your own desktop time field, for example one that always blocks certain hours. Pick it over useMuiXTimePickerAdapter when you want the desktop popover on every device, including touch screens.

This MeetingTimeField rejects any time in the 12:00 hour. The popover greys that hour out, but you can still type 12:30 PM into the field and submit to see the error.

hh:mm aa

Type a time or use the clock button

'use client';import Stack from '@mui/material/Stack';import { DesktopTimePicker, LocalizationProvider } from '@mui/x-date-pickers';import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';import { MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useMuiXDesktopTimePickerAdapter } from '@piplup/rhf-adapters/mui-x-date-pickers';import { useForm } from 'react-hook-form';import type { Dayjs } from 'dayjs';import type { Control } from 'react-hook-form';type FormValues = { meeting: Dayjs | null };// The 12:00 hour is lunch. The clock greys it out, and a typed 12:xx time// fails validation with the "shouldDisableTime-hours" message.function MeetingTimeField({ control }: { control: Control<FormValues> }) {  const adapter = useMuiXDesktopTimePickerAdapter<Dayjs, FormValues, 'meeting', HTMLDivElement>({    composeHelperText: true,    control,    messages: {      required: 'Pick a meeting time',      'shouldDisableTime-hours': 'No meetings over lunch (12:00 to 13:00)',    },    name: 'meeting',    required: true,    shouldDisableTime: (value, view) => view === 'hours' && value.hour() === 12,    slotProps: {      textField: { helperText: 'Type a time or use the clock button' },    },  });  return <DesktopTimePicker label="Meeting time" {...adapter} />;}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { meeting: null },  });  return (    <LocalizationProvider dateAdapter={AdapterDayjs}>      <form onSubmit={handleSubmit((values) => alert(values.meeting?.format('h:mm A')))} noValidate>        <Stack direction="column" spacing={2}>          <MeetingTimeField control={control} />          <div>            <MuiButtonElement control={control} type="submit" variant="contained">              Schedule            </MuiButtonElement>          </div>        </Stack>      </form>    </LocalizationProvider>  );}

What differs is the component you spread it onto:

  • TimePicker switches between the desktop and mobile layouts with the @media (pointer: fine) media query. DesktopTimePicker always uses the desktop layout.
  • The desktop popover shows a DigitalClock (one column) or a MultiSectionDigitalClock (one column per section), depending on the views and timeSteps. Both disable the options that minTime, maxTime, minutesStep and shouldDisableTime reject, because the hook returns those props.
  • The text field is the main way to enter a time. A typed time never goes through the disabled options in the popover, so validation is what rejects it.

shouldDisableTime and its message. Validation calls shouldDisableTime(value, view) with "hours", then "minutes", then "seconds", and reports the first view that returns true. Return true only for the view you mean, and override the matching key. The example checks view === "hours", so its error comes from shouldDisableTime-hours; the default for that key is "Hour is disabled".

MobileTimePicker

useMuiXMobileTimePickerAdapter returns props for MobileTimePicker. Use it when you build your own touch-first time field, for example a same-day booking field that always rejects times that have passed. Pick it over useMuiXTimePickerAdapter when you want the dialog on every device, including desktops with a mouse.

This PickupTimeField only accepts times later today. Open the dialog and pick a time that has already passed, then submit.

hh:mm aa

Tap to open the clock

'use client';import Stack from '@mui/material/Stack';import { LocalizationProvider, MobileTimePicker } from '@mui/x-date-pickers';import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';import { MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useMuiXMobileTimePickerAdapter } from '@piplup/rhf-adapters/mui-x-date-pickers';import { useForm } from 'react-hook-form';import type { Dayjs } from 'dayjs';import type { Control } from 'react-hook-form';type FormValues = { pickup: Dayjs | null };// Same-day pickup: the chosen time must still be ahead of now.function PickupTimeField({ control }: { control: Control<FormValues> }) {  const adapter = useMuiXMobileTimePickerAdapter<Dayjs, FormValues, 'pickup', HTMLDivElement>({    composeHelperText: true,    control,    disablePast: true,    messages: {      disablePast: 'That time has already passed today',      required: 'Choose a pickup time',    },    name: 'pickup',    required: true,    slotProps: {      textField: { helperText: 'Tap to open the clock' },    },  });  return <MobileTimePicker label="Pickup time (today)" {...adapter} />;}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { pickup: null },  });  return (    <LocalizationProvider dateAdapter={AdapterDayjs}>      <form onSubmit={handleSubmit((values) => alert(values.pickup?.format('h:mm A')))} noValidate>        <Stack direction="column" spacing={2}>          <PickupTimeField control={control} />          <div>            <MuiButtonElement control={control} type="submit" variant="contained">              Confirm pickup            </MuiButtonElement>          </div>        </Stack>      </form>    </LocalizationProvider>  );}

What differs is the component you spread it onto:

  • TimePicker picks the mobile layout only when the @media (pointer: fine) media query does not match. MobileTimePicker always uses it.
  • The hours, minutes and seconds views render as an analog TimeClock inside a dialog, not the digital lists of the desktop popover. The clock disables the hours and minutes that minTime, maxTime, minutesStep and shouldDisableTime reject.
  • Errors still render under the text field, through slotProps.textField, not inside the dialog.
  • The returned onClose runs when the dialog closes, which calls React Hook Form's onBlur and marks the field as touched. With mode: "onBlur" or "onTouched", validation runs right after the user closes the dialog.

disablePast and disableFuture compare the full date and time. Unlike minTime and maxTime, they do not ignore the date part. A value picked in the dialog keeps the date of the current value, or today's date when the field is empty, so in the example "past" means earlier today. If the form value carries another date, the check uses that date.

StaticTimePicker

useMuiXStaticTimePickerAdapter returns props for StaticTimePicker. MuiXStaticTimePickerElement renders the picker only, so it never shows an error message. Use the hook when you want the always-visible picker and also want to show validation errors next to it.

This ReportTimeField requires a time no later than 20:00 and shows the error below the picker. Submit without picking a time, or pick 21:00, to see it.

Select time
:
001234567891011121314151617181920212223

Reports go out once a day, no later than 20:00

'use client';import FormHelperText from '@mui/material/FormHelperText';import Stack from '@mui/material/Stack';import { LocalizationProvider, StaticTimePicker } from '@mui/x-date-pickers';import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';import { MuiButtonElement } from '@piplup/rhf-adapters/mui-material';import { useMuiXStaticTimePickerAdapter } from '@piplup/rhf-adapters/mui-x-date-pickers';import dayjs from 'dayjs';import { useForm } from 'react-hook-form';import type { Dayjs } from 'dayjs';import type { Control } from 'react-hook-form';type FormValues = { reportTime: Dayjs | null };const lastSend = dayjs().hour(20).minute(0);// A static picker has no text field, so this component renders the// error message itself, below the picker.function ReportTimeField({ control }: { control: Control<FormValues> }) {  const { error, helperText, ...adapter } = useMuiXStaticTimePickerAdapter<    Dayjs,    FormValues,    'reportTime',    HTMLDivElement  >({    composeHelperText: true,    control,    maxTime: lastSend,    messages: {      maxTime: "Reports can't be sent after 20:00",      required: 'Pick a time for the daily report',    },    name: 'reportTime',    required: true,  });  return (    <div>      <StaticTimePicker ampm={false} {...adapter} />      <FormHelperText error={error}>        {helperText || 'Reports go out once a day, no later than 20:00'}      </FormHelperText>    </div>  );}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { reportTime: null },  });  return (    <LocalizationProvider dateAdapter={AdapterDayjs}>      <form        onSubmit={handleSubmit((values) => alert(values.reportTime?.format('HH:mm')))}        noValidate      >        <Stack direction="column" spacing={2}>          <ReportTimeField control={control} />          <div>            <MuiButtonElement control={control} type="submit" variant="contained">              Save schedule            </MuiButtonElement>          </div>        </Stack>      </form>    </LocalizationProvider>  );}
  • There is no slotProps, inputRef or onClose in the result, and the hook does not accept them.
  • The result has plain error and helperText values. With composeHelperText: true, helperText is the current error message, or undefined when the field is valid. There is no helperText prop, so put any hint in your own markup, as the example does with helperText || "...".
  • The hook's second argument is merged with React Hook Form's ref and returned as ref.

Take error and helperText out of the result before spreading it, and render them yourself, for example with FormHelperText. The element drops them for the same reason.

A static picker is never closed and has no input to blur, so nothing calls the returned onBlur and the field is never marked as touched. mode: "onBlur" and "onTouched" first validate on submit. Use mode: "onChange" to show errors while the user picks.

When the value changes. By default StaticTimePicker uses displayStaticWrapperAs="mobile": an analog clock with a toolbar. The value reaches the form through onChange each time the user changes the clock, not only when they accept it.

Props and return value. The static hook takes no slotProps, inputRef or onClose:

Prop

Type

Prop

Type

Props

Prop

Type

Return value

Prop

Type

On this page