Introducing PrimeReact v11-alpha 🎉Discover Now

useDatePicker

Hook that manages date picker state, calendar navigation, view switching, and popup positioning.

basic-demo

Usage#

import { useDatePicker } from '@primereact/headless/datepicker';
import { usePortal } from '@primereact/headless/portal';
import { usePositioner } from '@primereact/headless/positioner';
 
const datepicker = useDatePicker({ ...options });
const {
    rootProps,
    inputProps,
    triggerProps,
    popupProps,
    positionerProps,
    panelProps,
    calendarProps,
    headerProps,
    titleProps,
    prevProps,
    nextProps,
    selectMonthProps,
    selectYearProps,
    decadeProps,
    getTableProps,
    tableHeaderProps,
    tableHeaderRowProps,
    weekDayCellProps,
    tableBodyProps,
    tableBodyRowProps,
    getTableBodyCellProps,
    getDayProps,
    getMonthProps,
    getYearProps,
    state,
    months,
    weekDays,
    monthPickerValues,
    yearPickerValues,
    getMonthName,
    getYear
} = datepicker;
const portal = usePortal();
 
usePositioner({
    anchor: state.anchorElement,
    content: state.positionerElement,
    side: 'bottom',
    flip: true,
    shift: true
});
 
return (
    <div {...rootProps}>
        <input {...inputProps} />
        <button {...triggerProps}></button>
        {portal.state.mounted &&
            state.opened &&
            createPortal(
                <div {...positionerProps}>
                    <div {...popupProps}>
                        <div {...panelProps}>
                            <div {...calendarProps}>
                                {/* Header: prev / title / next */}
                                <div {...headerProps}>
                                    <button {...prevProps}></button>
                                    <div {...titleProps}>
                                        <button {...selectMonthProps}>{getMonthName()}</button>
                                        <button {...selectYearProps}>{getYear()}</button>
                                    </div>
                                    <button {...nextProps}></button>
                                </div>
 
                                {/* Date view */}
                                {months.map((month, groupIndex) => (
                                    <table {...getTableProps()}>
                                        <thead {...tableHeaderProps}>
                                            <tr {...tableHeaderRowProps}>
                                                {weekDays.map((day, i) => (
                                                    <th key={i} {...weekDayCellProps}></th>
                                                ))}
                                            </tr>
                                        </thead>
                                        <tbody {...tableBodyProps}>
                                            {month.dates.map((week, wi) => (
                                                <tr key={wi} {...tableBodyRowProps}>
                                                    {week.map((date, di) => (
                                                        <td key={di} {...getTableBodyCellProps(date)}>
                                                            <span {...getDayProps(date, groupIndex)}>{date.day}</span>
                                                        </td>
                                                    ))}
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                ))}
 
                                {/* Month view */}
                                {monthPickerValues.map((m, i) => (
                                    <span {...getMonthProps(m, i)}>{m.value}</span>
                                ))}
 
                                {/* Year view */}
                                {yearPickerValues.map((y) => (
                                    <span {...getYearProps(y)}>{y.value}</span>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>,
                document.body
            )}
    </div>
);

useDatePicker composes usePopover internally, managing calendar state, date selection, and keyboard navigation — see Primitive for a component-based API.

Features#

  • rootProps, inputProps, triggerProps, popupProps, positionerProps, arrowProps, panelProps, calendarProps, headerProps, and 30+ additional spread-ready prop objects cover every UI section
  • getDayProps(), getMonthProps(), getYearProps() return cell-level props with selection state, event handlers, and ARIA attributes
  • getTableProps(), getTableBodyCellProps(), getIncrementProps(), getDecrementProps(), getPickerProps() for dynamic table and time picker elements
  • months, weekDays, monthPickerValues, yearPickerValues provide calendar data for rendering grids
  • show(), hide(), toggle() for imperative popup control
  • switchToMonthView(), switchToYearView() for programmatic view changes
  • formattedCurrentHour, formattedCurrentMinute, formattedCurrentSecond, ampmLabel for time display
  • parseValue(), isSelected(), isDateEquals(), isInHoverRange() for custom rendering logic

Behavior#

Default Value#

Set defaultValue for uncontrolled selection.

const datepicker = useDatePicker({ defaultValue: new Date() });

Controlled#

Pass value and onValueChange for controlled selection state.

const [date, setDate] = React.useState(null);
 
const datepicker = useDatePicker({
    value: date,
    onValueChange: (e) => setDate(e.value)
});

Selection Mode#

Set selectionMode to 'multiple' or 'range' for multi-date or range selection. The value becomes an array.

const datepicker = useDatePicker({ selectionMode: 'range' });

Date Format#

Set dateFormat to customize the display format. Tokens include d, dd, m, mm, M, MM, y, yy, and more.

const datepicker = useDatePicker({ dateFormat: 'dd/mm/yy' });

View#

Set view to 'month' or 'year' to start in month or year picker mode.

const datepicker = useDatePicker({ view: 'month', dateFormat: 'mm/yy' });

Min / Max#

Set minDate and maxDate to constrain selectable dates.

const datepicker = useDatePicker({ minDate: new Date(2024, 0, 1), maxDate: new Date(2024, 11, 31) });

Disabled Dates#

Pass disabledDates for specific dates or disabledDays for recurring weekdays.

const datepicker = useDatePicker({ disabledDays: [0, 6] });

Time Picker#

Set showTime to display time controls alongside the calendar, or timeOnly to show only time.

const datepicker = useDatePicker({ showTime: true, hourFormat: '12' });

Multiple Months#

Set numberOfMonths to display multiple calendar months side by side.

const datepicker = useDatePicker({ numberOfMonths: 2 });

Use open and onOpenChange for controlled popup state, or defaultOpen for uncontrolled initial state.

const [open, setOpen] = React.useState(false);
 
const datepicker = useDatePicker({
    open,
    onOpenChange: (e) => setOpen(e.value)
});

Set closeOnEscape to dismiss the overlay with the Escape key, autoFocus to move focus into the overlay when it opens, and trapped to keep focus within the overlay.

const datepicker = useDatePicker({ closeOnEscape: true, autoFocus: true, trapped: true });

Custom Styling with Data Attributes#

Every prop object includes data-scope="datepicker" and a data-part that identifies the element. State-driven attributes appear or disappear automatically.

PartState Attributes
rootdata-disabled, data-invalid, data-readonly
daydata-selected, data-disabled, data-today, data-other-month
monthdata-selected, data-disabled
yeardata-selected, data-disabled
popupdata-open
/* Selected day */
[data-scope='datepicker'][data-part='day'][data-selected='true'] {
    background: var(--p-primary-color);
    color: var(--p-primary-contrast-color);
}
 
/* Today indicator */
[data-scope='datepicker'][data-part='day'][data-today='true'] {
    font-weight: 600;
    color: var(--p-primary-color);
}
 
/* Disabled date */
[data-scope='datepicker'][data-part='day'][data-disabled='true'] {
    opacity: 0.4;
    pointer-events: none;
}

API#

useDatePicker#

NameTypeDefault
valuestring | string[] | Date | Date[]—
Value of the component.
defaultValuestring | string[] | Date | Date[]—
The default value for the input when not controlled by `modelValue` .
openboolean—
Controlled open state of the input tags overlay.
defaultOpenboolean—
Default open state for uncontrolled mode.
namestring—
The name attribute for the element, typically used in form submissions.
selectionMode"multiple" | "range" | "single"single
Defines the quantity of the selection.
dateFormatstring—
Format of the date. Defaults to PrimeVue Locale configuration.
updateModelType"string" | "date"date
Type of the value to write back to modelValue.
selectOtherMonthsbooleanfalse
Whether days in other months shown before or after the current month are selectable. This only applies if the showOtherMonths option is set to true.
showIconbooleanfalse
When enabled, displays a button with icon next to input.
iconstring—
Icon of the datepicker button.
prevIconstring—
Icon to show in the previous button.
nextIconstring—
Icon to show in the next button.
incrementIconstring—
Icon to show in each of the increment buttons.
decrementIconstring—
Icon to show in each of the decrement buttons.
numberOfMonthsnumber1
Number of months to display.
breakpointstring769px
The breakpoint to define the maximum width boundary for datepicker panel.
view"date" | "month" | "year"date
Type of view to display.
minDateDate—
The minimum selectable date.
maxDateDate—
The maximum selectable date.
disabledDatesDate[]—
Array with dates to disable.
disabledDaysnumber[]—
Array with disabled weekday numbers.
maxDateCountnumber—
Maximum number of selectable dates in multiple mode.
showOnFocusbooleantrue
When disabled, datepicker will not be visible with input focus.
autoZIndexbooleantrue
Whether to automatically manage layering.
baseZIndexnumber0
Base zIndex value to use in layering.
showButtonBarbooleanfalse
Whether to display today and clear buttons at the footer.
shortYearCutoffstring+10
The cutoff year for determining the century for a date.
showTimebooleanfalse
Whether to display timepicker.
timeOnlybooleanfalse
Whether to display timepicker only.
hourFormat"12" | "24"24
Specifies hour format.
stepHournumber1
Hours to change per step.
stepMinutenumber1
Minutes to change per step.
stepSecondnumber1
Seconds to change per step.
showSecondsbooleanfalse
Whether to show the seconds in time picker.
showWeekbooleanfalse
Whether to display week numbers.
hideOnDateTimeSelectbooleanfalse
Whether to hide the overlay on date selection when showTime is enabled.
hideOnRangeSelectionbooleanfalse
Whether to hide the overlay on date selection is completed when selectionMode is range.
timeSeparatorstring:
Separator of time selector.
manualInputbooleantrue
Whether to allow entering the date manually via typing.
size"small" | "large"—
Defines the size of the component.
invalidbooleanfalse
When present, it specifies that the component should have invalid state style.
disabledbooleanfalse
When present, it specifies that the component should be disabled.
variant"outlined" | "filled"—
Specifies the input variant of the component.
readOnlybooleanfalse
When present, it specifies that an input field is read-only.
placeholderstring—
Placeholder text for the input.
requiredboolean—
When present, it specifies that the component is a required field.
appendTo"body" | HTMLElement | "self"body
A valid query selector or an HTMLElement to specify where the overlay gets attached.
fluidboolean—
Spans 100% width of the container when enabled.
ariaLabelledbystring—
Establishes relationships between the component and label(s) where its value should be one or more element IDs.
ariaLabelstring—
Establishes a string value that labels the component.
onValueChange(event: useDatePickerValueChangeEvent) => void—
Callback to invoke when the value changes.
onDateSelect(event: useDatePickerDateSelectEvent) => void—
Callback to invoke when a date is selected.
onMonthChange(event: useDatePickerMonthChangeEvent) => void—
Callback to invoke when the month changes.
onYearChange(event: useDatePickerYearChangeEvent) => void—
Callback to invoke when the year changes.
onTodayButtonClick(event: useDatePickerTodayButtonClickEvent) => void—
Callback to invoke when the today button is clicked.
onClearButtonClick(event: MouseEvent<HTMLButtonElement>) => void—
Callback to invoke when the clear button is clicked.
onInput(event: ChangeEvent<HTMLInputElement>) => void—
Callback to invoke on input event.
onKeyDown(event: KeyboardEvent<HTMLButtonElement | HTMLInputElement>) => void—
Callback to invoke on keydown event.
onFocus(event: FocusEvent<HTMLInputElement>) => void—
Callback to invoke on focus event.
onBlur(event: useDatePickerBlurEvent) => void—
Callback to invoke on blur event.
onOpenChange(event: useDatePickerOpenChangeEvent) => void—
Callback to invoke when the open state changes.
closeOnEscapebooleantrue
Specifies if pressing escape key should hide the overlay.
autoFocusbooleanfalse
Whether to focus the first focusable element when the overlay is opened.
trappedbooleanfalse
When enabled, focus is trapped within the overlay (modal behavior).

Accessibility#

See DatePicker Primitive for WAI-ARIA compliance details and keyboard support.