DatePicker
A date picker combines a DateField and a Calendar popover to allow users to enter or select a date and time value.
install | yarn add react-aria-components |
---|---|
version | 3.17.0 |
usage | import {DatePicker} from 'react-aria-components' |
Example#
import {Button, Calendar, CalendarCell, CalendarGrid, DateInput, DatePicker, DateSegment, Dialog, Group, Heading, Label, Popover} from 'react-aria-components';
<DatePicker>
<Label>Date</Label>
<Group>
<DateInput>
{(segment) => <DateSegment segment={segment} />}
</DateInput>
<Button>▼</Button>
</Group>
<Popover>
<Dialog>
<Calendar>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
</Calendar>
</Dialog>
</Popover>
</DatePicker>
import {
Button,
Calendar,
CalendarCell,
CalendarGrid,
DateInput,
DatePicker,
DateSegment,
Dialog,
Group,
Heading,
Label,
Popover
} from 'react-aria-components';
<DatePicker>
<Label>Date</Label>
<Group>
<DateInput>
{(segment) => <DateSegment segment={segment} />}
</DateInput>
<Button>▼</Button>
</Group>
<Popover>
<Dialog>
<Calendar>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
</Calendar>
</Dialog>
</Popover>
</DatePicker>
import {
Button,
Calendar,
CalendarCell,
CalendarGrid,
DateInput,
DatePicker,
DateSegment,
Dialog,
Group,
Heading,
Label,
Popover
} from 'react-aria-components';
<DatePicker>
<Label>Date</Label>
<Group>
<DateInput>
{(segment) => (
<DateSegment
segment={segment}
/>
)}
</DateInput>
<Button>▼</Button>
</Group>
<Popover>
<Dialog>
<Calendar>
<header>
<Button slot="previous">
◀
</Button>
<Heading />
<Button slot="next">
▶
</Button>
</header>
<CalendarGrid>
{(date) => (
<CalendarCell
date={date}
/>
)}
</CalendarGrid>
</Calendar>
</Dialog>
</Popover>
</DatePicker>
Show CSS
.react-aria-DatePicker {
& [role=group] {
display: flex;
width: fit-content;
align-items: center;
}
& button {
background: slateblue;
color: white;
border-radius: 4px;
border: none;
appearance: none;
margin-left: -27px;
width: 1.429rem;
height: 1.429rem;
padding: 0;
vertical-align: middle;
font-size: 0.857rem;
outline: none;
box-sizing: content-box;
border: 2px solid var(--page-background);
&[data-focus-visible] {
box-shadow: 0 0 0 2px slateblue;
}
}
& [slot=description] {
font-size: 12px;
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-DateInput {
display: flex;
padding: 4px 2.5rem 4px 8px;
border: 1px solid var(--spectrum-global-color-gray-400);
border-radius: 6px;
background: var(--spectrum-global-color-gray-50);
width: fit-content;
min-width: 150px;
&:focus-within {
border-color: slateblue;
box-shadow: 0 0 0 1px slateblue;
}
}
.react-aria-DateSegment {
padding: 0 2px;
font-variant-numeric: tabular-nums;
text-align: end;
&[data-type=literal] {
padding: 0;
}
&[data-placeholder] {
color: var(--spectrum-global-color-gray-700);
font-style: italic;
}
&:focus {
color: white;
background: slateblue;
outline: none;
border-radius: 4px;
caret-color: transparent;
}
&[aria-invalid] {
color: var(--spectrum-global-color-red-600);
&:focus {
background: var(--spectrum-global-color-static-red-600);
color: white;
}
}
}
.react-aria-Popover {
overflow: auto;
border: 1px solid var(--spectrum-global-color-gray-400);
box-shadow: 0 8px 20px rgba(0 0 0 / 0.1);
border-radius: 6px;
background: var(--page-background);
padding: 1.25rem;
}
.react-aria-Calendar {
& header {
display: flex;
align-items: center;
margin-bottom: .5rem;
& h2 {
flex: 1;
margin: 0;
text-align: center;
font-size: 1.375rem;
}
& button {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
box-shadow: 0 1px 2px rgba(0 0 0 / 0.1);
border-radius: 4px;
appearance: none;
vertical-align: middle;
font-size: 1rem;
width: 1.75rem;
height: 1.75rem;
text-align: center;
margin: 0;
outline: none;
&[data-focus-visible] {
border-color: slateblue;
box-shadow: 0 0 0 1px slateblue;
}
&[data-pressed] {
background: var(--spectrum-global-color-gray-100);
}
}
}
& table {
margin: 0 -4px;
}
& .react-aria-CalendarCell {
width: 2rem;
line-height: 2rem;
text-align: center;
border-radius: 6px;
cursor: default;
outline: none;
border: 2px solid var(--page-background);
margin: -1px;
&[data-outside-month] {
display: none;
}
&[data-pressed] {
background: var(--spectrum-global-color-gray-200);
}
&[data-focus-visible] {
box-shadow: 0 0 0 2px slateblue;
}
&[data-selected] {
background: slateblue;
color: white;
}
&[data-disabled] {
color: var(--spectrum-global-color-gray-600);
}
&[data-unavailable] {
text-decoration: line-through;
color: var(--spectrum-global-color-red-600);
}
&[aria-invalid] {
background: var(--spectrum-global-color-static-red-600);
color: white;
}
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-DatePicker {
& [role=group] {
display: flex;
width: fit-content;
align-items: center;
}
& button {
background: slateblue;
color: white;
border-radius: 4px;
border: none;
appearance: none;
margin-left: -27px;
width: 1.429rem;
height: 1.429rem;
padding: 0;
vertical-align: middle;
font-size: 0.857rem;
outline: none;
box-sizing: content-box;
border: 2px solid var(--page-background);
&[data-focus-visible] {
box-shadow: 0 0 0 2px slateblue;
}
}
& [slot=description] {
font-size: 12px;
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-DateInput {
display: flex;
padding: 4px 2.5rem 4px 8px;
border: 1px solid var(--spectrum-global-color-gray-400);
border-radius: 6px;
background: var(--spectrum-global-color-gray-50);
width: fit-content;
min-width: 150px;
&:focus-within {
border-color: slateblue;
box-shadow: 0 0 0 1px slateblue;
}
}
.react-aria-DateSegment {
padding: 0 2px;
font-variant-numeric: tabular-nums;
text-align: end;
&[data-type=literal] {
padding: 0;
}
&[data-placeholder] {
color: var(--spectrum-global-color-gray-700);
font-style: italic;
}
&:focus {
color: white;
background: slateblue;
outline: none;
border-radius: 4px;
caret-color: transparent;
}
&[aria-invalid] {
color: var(--spectrum-global-color-red-600);
&:focus {
background: var(--spectrum-global-color-static-red-600);
color: white;
}
}
}
.react-aria-Popover {
overflow: auto;
border: 1px solid var(--spectrum-global-color-gray-400);
box-shadow: 0 8px 20px rgba(0 0 0 / 0.1);
border-radius: 6px;
background: var(--page-background);
padding: 1.25rem;
}
.react-aria-Calendar {
& header {
display: flex;
align-items: center;
margin-bottom: .5rem;
& h2 {
flex: 1;
margin: 0;
text-align: center;
font-size: 1.375rem;
}
& button {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
box-shadow: 0 1px 2px rgba(0 0 0 / 0.1);
border-radius: 4px;
appearance: none;
vertical-align: middle;
font-size: 1rem;
width: 1.75rem;
height: 1.75rem;
text-align: center;
margin: 0;
outline: none;
&[data-focus-visible] {
border-color: slateblue;
box-shadow: 0 0 0 1px slateblue;
}
&[data-pressed] {
background: var(--spectrum-global-color-gray-100);
}
}
}
& table {
margin: 0 -4px;
}
& .react-aria-CalendarCell {
width: 2rem;
line-height: 2rem;
text-align: center;
border-radius: 6px;
cursor: default;
outline: none;
border: 2px solid var(--page-background);
margin: -1px;
&[data-outside-month] {
display: none;
}
&[data-pressed] {
background: var(--spectrum-global-color-gray-200);
}
&[data-focus-visible] {
box-shadow: 0 0 0 2px slateblue;
}
&[data-selected] {
background: slateblue;
color: white;
}
&[data-disabled] {
color: var(--spectrum-global-color-gray-600);
}
&[data-unavailable] {
text-decoration: line-through;
color: var(--spectrum-global-color-red-600);
}
&[aria-invalid] {
background: var(--spectrum-global-color-static-red-600);
color: white;
}
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-DatePicker {
& [role=group] {
display: flex;
width: fit-content;
align-items: center;
}
& button {
background: slateblue;
color: white;
border-radius: 4px;
border: none;
appearance: none;
margin-left: -27px;
width: 1.429rem;
height: 1.429rem;
padding: 0;
vertical-align: middle;
font-size: 0.857rem;
outline: none;
box-sizing: content-box;
border: 2px solid var(--page-background);
&[data-focus-visible] {
box-shadow: 0 0 0 2px slateblue;
}
}
& [slot=description] {
font-size: 12px;
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-DateInput {
display: flex;
padding: 4px 2.5rem 4px 8px;
border: 1px solid var(--spectrum-global-color-gray-400);
border-radius: 6px;
background: var(--spectrum-global-color-gray-50);
width: fit-content;
min-width: 150px;
&:focus-within {
border-color: slateblue;
box-shadow: 0 0 0 1px slateblue;
}
}
.react-aria-DateSegment {
padding: 0 2px;
font-variant-numeric: tabular-nums;
text-align: end;
&[data-type=literal] {
padding: 0;
}
&[data-placeholder] {
color: var(--spectrum-global-color-gray-700);
font-style: italic;
}
&:focus {
color: white;
background: slateblue;
outline: none;
border-radius: 4px;
caret-color: transparent;
}
&[aria-invalid] {
color: var(--spectrum-global-color-red-600);
&:focus {
background: var(--spectrum-global-color-static-red-600);
color: white;
}
}
}
.react-aria-Popover {
overflow: auto;
border: 1px solid var(--spectrum-global-color-gray-400);
box-shadow: 0 8px 20px rgba(0 0 0 / 0.1);
border-radius: 6px;
background: var(--page-background);
padding: 1.25rem;
}
.react-aria-Calendar {
& header {
display: flex;
align-items: center;
margin-bottom: .5rem;
& h2 {
flex: 1;
margin: 0;
text-align: center;
font-size: 1.375rem;
}
& button {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
box-shadow: 0 1px 2px rgba(0 0 0 / 0.1);
border-radius: 4px;
appearance: none;
vertical-align: middle;
font-size: 1rem;
width: 1.75rem;
height: 1.75rem;
text-align: center;
margin: 0;
outline: none;
&[data-focus-visible] {
border-color: slateblue;
box-shadow: 0 0 0 1px slateblue;
}
&[data-pressed] {
background: var(--spectrum-global-color-gray-100);
}
}
}
& table {
margin: 0 -4px;
}
& .react-aria-CalendarCell {
width: 2rem;
line-height: 2rem;
text-align: center;
border-radius: 6px;
cursor: default;
outline: none;
border: 2px solid var(--page-background);
margin: -1px;
&[data-outside-month] {
display: none;
}
&[data-pressed] {
background: var(--spectrum-global-color-gray-200);
}
&[data-focus-visible] {
box-shadow: 0 0 0 2px slateblue;
}
&[data-selected] {
background: slateblue;
color: white;
}
&[data-disabled] {
color: var(--spectrum-global-color-gray-600);
}
&[data-unavailable] {
text-decoration: line-through;
color: var(--spectrum-global-color-red-600);
}
&[aria-invalid] {
background: var(--spectrum-global-color-static-red-600);
color: white;
}
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
Features#
A date picker can be built using <input type="date">
, but this is very limited in functionality, lacking in internationalization capabilities, inconsistent between browsers, and difficult to style. DatePicker
helps achieve accessible and international date and time pickers that can be styled as needed.
- Dates and times – Support for dates and times with configurable granularity.
- International – Support for 13 calendar systems used around the world, including Gregorian, Buddhist, Islamic, Persian, and more. Locale-specific formatting, number systems, hour cycles, and right-to-left support are available as well.
- Time zone aware – Dates and times can optionally include a time zone. All modifications follow time zone rules such as daylight saving time.
- Accessible – Each date and time unit is displayed as an individually focusable and editable segment, which allows users an easy way to edit dates using the keyboard, in any date format and locale. Users can also open a calendar popover to select dates in a standard month grid. Localized screen reader messages are included to announce when the selection and visible date range change.
- Touch friendly – Date segments are editable using an easy to use numeric keypad, and all interactions are accessible using touch-based screen readers.
- Customizable – As with all of React Aria, the DOM structure and styling of all elements can be fully customized.
Read our blog post for more details about the internationalization, accessibility, and user experience features implemented by DatePicker
.
Anatomy#
A date picker consists of a label, and group containing a date field and a button. Clicking the button opens a popup containing a calendar. The date field includes segments representing each unit of a date and time (e.g. years, months, days, etc.), each of which is individually focusable and editable using the keyboard. The calendar popup offers a more visual way of choosing a date.
DatePicker
also supports optional description and error message elements, which can be used to provide more context about the field, and any validation messages. These are linked with the input via the aria-describedby
attribute.
If the date picker does not have a visible label, an aria-label
or aria-labelledby
prop must be passed instead to identify it to assistive technology.
Note that most of this anatomy is shared with DateRangePicker, so you can reuse many components between them if you have both.
Concepts#
DatePicker
makes use of the following concepts:
Composed components#
A DatePicker
uses the following components, which may also be used standalone or reused in other components.
Props#
DatePicker#
Name | Type | Default | Description |
minValue | DateValue | — | The minimum allowed date that a user may select. |
maxValue | DateValue | — | The maximum allowed date that a user may select. |
isDateUnavailable | (
(date: DateValue
)) => boolean | — | Callback that is called for each date of the calendar. If it returns true, then the date is unavailable. |
placeholderValue | DateValue | — | A placeholder date that influences the format of the placeholder shown when no value is selected. Defaults to today's date at midnight. |
hourCycle | 12 | 24 | — | Whether to display the time in 12 or 24 hour format. By default, this is determined by the user's locale. |
granularity | Granularity | — | Determines the smallest unit that is displayed in the date picker. By default, this is "day" for dates, and "minute" for times. |
hideTimeZone | boolean | false | Whether to hide the time zone abbreviation. |
isDisabled | boolean | — | Whether the input is disabled. |
isReadOnly | boolean | — | Whether the input can be selected but not changed by the user. |
validationState | ValidationState | — | Whether the input should display its "valid" or "invalid" visual styling. |
isRequired | boolean | — | Whether user input is required on the input before form submission.
Often paired with the |
autoFocus | boolean | — | Whether the element should receive focus on render. |
isOpen | boolean | — | Whether the overlay is open by default (controlled). |
defaultOpen | boolean | — | Whether the overlay is open by default (uncontrolled). |
value | DateValue | — | The current value (controlled). |
defaultValue | DateValue | — | The default value (uncontrolled). |
children | ReactNode | (
(values: DatePickerState
)) => ReactNode | — | |
className | string | (
(values: DatePickerState
)) => string | — | |
style | CSSProperties | (
(values: DatePickerState
)) => CSSProperties | — |
Events
Name | Type | Default | Description |
onFocus | (
(e: FocusEvent
)) => void | — | Handler that is called when the element receives focus. |
onBlur | (
(e: FocusEvent
)) => void | — | Handler that is called when the element loses focus. |
onFocusChange | (
(isFocused: boolean
)) => void | — | Handler that is called when the element's focus status changes. |
onKeyDown | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is pressed. |
onKeyUp | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is released. |
onOpenChange | (
(isOpen: boolean
)) => void | — | Handler that is called when the overlay's open state changes. |
onChange | (
(value: MappedDateValue<DateValue>
)) => void | — | Handler that is called when the value changes. |
Accessibility
Name | Type | Default | Description |
id | string | — | The element's unique identifier. See MDN. |
aria-label | string | — | Defines a string value that labels the current element. |
aria-labelledby | string | — | Identifies the element (or elements) that labels the current element. |
aria-describedby | string | — | Identifies the element (or elements) that describes the object. |
aria-details | string | — | Identifies the element (or elements) that provide a detailed, extended description for the object. |
Label#
A <Label>
accepts all HTML attributes.
Group#
A <Group>
accepts all HTML attributes.
DateInput#
The <DateInput>
component renders a group of date segments. It accepts a function as its children
, which is called to render a <DateSegment>
for each segment.
Show props
Name | Type | Default | Description |
children | (
(segment: DateSegment
)) => ReactElement | — | |
className | string | — | |
style | CSSProperties | — |
Layout
Name | Type | Default | Description |
slot | string | — |
DateSegment#
The <DateSegment>
component renders an individual segment.
Show props
Name | Type | Default | Description |
segment | DateSegment | — | |
children | ReactNode | (
(values: DateSegmentRenderProps
)) => ReactNode | — | |
className | string | (
(values: DateSegmentRenderProps
)) => string | — | |
style | CSSProperties | (
(values: DateSegmentRenderProps
)) => CSSProperties | — |
Button#
A <Button>
accepts its contents as children
. Other props such as onPress
and isDisabled
will be set by the DatePicker
or Calendar
.
Show props
Name | Type | Default | Description |
isDisabled | boolean | — | Whether the button is disabled. |
autoFocus | boolean | — | Whether the element should receive focus on render. |
type | 'button'
| 'submit'
| 'reset' | 'button' | The behavior of the button when used in an HTML form. |
children | ReactNode | (
(values: ButtonRenderProps
)) => ReactNode | — | |
className | string | (
(values: ButtonRenderProps
)) => string | — | |
style | CSSProperties | (
(values: ButtonRenderProps
)) => CSSProperties | — |
Events
Name | Type | Default | Description |
onPress | (
(e: PressEvent
)) => void | — | Handler that is called when the press is released over the target. |
onPressStart | (
(e: PressEvent
)) => void | — | Handler that is called when a press interaction starts. |
onPressEnd | (
(e: PressEvent
)) => void | — | Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target. |
onPressChange | (
(isPressed: boolean
)) => void | — | Handler that is called when the press state changes. |
onPressUp | (
(e: PressEvent
)) => void | — | Handler that is called when a press is released over the target, regardless of whether it started on the target or not. |
onFocus | (
(e: FocusEvent
)) => void | — | Handler that is called when the element receives focus. |
onBlur | (
(e: FocusEvent
)) => void | — | Handler that is called when the element loses focus. |
onFocusChange | (
(isFocused: boolean
)) => void | — | Handler that is called when the element's focus status changes. |
onKeyDown | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is pressed. |
onKeyUp | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is released. |
Layout
Name | Type | Default | Description |
slot | string | — |
Accessibility
Name | Type | Default | Description |
id | string | — | The element's unique identifier. See MDN. |
excludeFromTabOrder | boolean | — | Whether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available. |
aria-expanded | boolean
| 'true'
| 'false' | — | Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. |
aria-haspopup | boolean
| 'menu'
| 'listbox'
| 'tree'
| 'grid'
| 'dialog'
| 'true'
| 'false' | — | Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. |
aria-controls | string | — | Identifies the element (or elements) whose contents or presence are controlled by the current element. |
aria-pressed | boolean
| 'true'
| 'false'
| 'mixed' | — | Indicates the current "pressed" state of toggle buttons. |
aria-label | string | — | Defines a string value that labels the current element. |
aria-labelledby | string | — | Identifies the element (or elements) that labels the current element. |
aria-describedby | string | — | Identifies the element (or elements) that describes the object. |
aria-details | string | — | Identifies the element (or elements) that provide a detailed, extended description for the object. |
Popover#
A <Popover>
is an overlay to hold the <Calendar>
, positioned relative to the <Group>
. By default, it has a placement
of bottom start
within a <DatePicker>
, but this and other positioning properties may be customized.
Show props
Name | Type | Default | Description |
triggerRef | RefObject<Element> | — | The ref for the element which the popover positions itself with respect to. When used within a trigger component such as DialogTrigger, MenuTrigger, Select, etc., this is set automatically. It is only required when used standalone. |
placement | Placement | 'bottom' | The placement of the element with respect to its anchor element. |
containerPadding | number | 12 | The placement padding that should be applied between the element and its surrounding container. |
offset | number | 0 | The additional offset applied along the main axis between the element and its anchor element. |
crossOffset | number | 0 | The additional offset applied along the cross axis between the element and its anchor element. |
shouldFlip | boolean | true | Whether the element should flip its orientation (e.g. top to bottom or left to right) when there is insufficient room for it to render completely. |
isNonModal | boolean | — | Whether the popover is non-modal, i.e. elements outside the popover may be interacted with by assistive technologies. Most popovers should not use this option as it may negatively impact the screen reader experience. Only use with components such as combobox, which are designed to handle this situation carefully. |
children | ReactNode | (
(values: PopoverRenderProps
)) => ReactNode | — | |
className | string | (
(values: PopoverRenderProps
)) => string | — | |
style | CSSProperties | (
(values: PopoverRenderProps
)) => CSSProperties | — |
Dialog#
A <Dialog>
is placed within a <Popover>
to hold the <Calendar>
for a DatePicker.
Show props
Name | Type | Default | Description |
children | ReactNode | — | |
className | string | — | |
style | CSSProperties | — |
Events
Name | Type | Default | Description |
onClose | () => void | — |
Accessibility
Name | Type | Default | Description |
role | 'dialog' | 'alertdialog' | 'dialog' | The accessibility role for the dialog. |
id | string | — | The element's unique identifier. See MDN. |
aria-label | string | — | Defines a string value that labels the current element. |
aria-labelledby | string | — | Identifies the element (or elements) that labels the current element. |
aria-describedby | string | — | Identifies the element (or elements) that describes the object. |
aria-details | string | — | Identifies the element (or elements) that provide a detailed, extended description for the object. |
Calendar#
A <Calendar>
accepts one or more month grids as chilren, along with previous and next buttons to navigate forward and backward.
Show props
Name | Type | Default | Description |
visibleDuration | DateDuration | {months: 1} | The amount of days that will be displayed at once. This affects how pagination works. |
minValue | DateValue | — | The minimum allowed date that a user may select. |
maxValue | DateValue | — | The maximum allowed date that a user may select. |
isDateUnavailable | (
(date: DateValue
)) => boolean | — | Callback that is called for each date of the calendar. If it returns true, then the date is unavailable. |
isDisabled | boolean | false | Whether the calendar is disabled. |
isReadOnly | boolean | false | Whether the calendar value is immutable. |
autoFocus | boolean | false | Whether to automatically focus the calendar when it mounts. |
focusedValue | DateValue | — | Controls the currently focused date within the calendar. |
defaultFocusedValue | DateValue | — | The date that is focused when the calendar first mounts (uncountrolled). |
validationState | ValidationState | — | Whether the current selection is valid or invalid according to application logic. |
value | DateValue | — | The current value (controlled). |
defaultValue | DateValue | — | The default value (uncontrolled). |
children | ReactNode | (
(values: CalendarState
)) => ReactNode | — | |
className | string | (
(values: CalendarState
)) => string | — | |
style | CSSProperties | (
(values: CalendarState
)) => CSSProperties | — |
Events
Name | Type | Default | Description |
onFocusChange | (
(date: CalendarDate
)) => void | — | Handler that is called when the focused date changes. |
onChange | (
(value: MappedDateValue<DateValue>
)) => void | — | Handler that is called when the value changes. |
CalendarGrid#
A <CalendarGrid>
renders an individual month within a <Calendar>
. It accepts a function as its children
, which is called to render a <CalendarCell>
for each date.
Show props
Name | Type | Default | Description |
children | (
(date: CalendarDate
)) => ReactElement | — | |
offset | DateDuration | — | |
className | string | — | |
style | CSSProperties | — |
CalendarCell#
A <CalendarCell>
renders an individual date within a <CalendarGrid>
.
Show props
Name | Type | Default | Description |
date | CalendarDate | — | |
children | ReactNode | (
(values: CalendarCellRenderProps
)) => ReactNode | — | |
className | string | (
(values: CalendarCellRenderProps
)) => string | — | |
style | CSSProperties | (
(values: CalendarCellRenderProps
)) => CSSProperties | — |
Styling#
React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin className
attribute which can be targeted using CSS selectors. These follow the react-aria-ComponentName
naming convention.
.react-aria-DatePicker {
/* ... */
}
.react-aria-DatePicker {
/* ... */
}
.react-aria-DatePicker {
/* ... */
}
A custom className
can also be specified on any component. This overrides the default className
provided by React Aria with your own.
<DateInput className="my-date-input">
{/* ... */}
</DateInput>
<DateInput className="my-date-input">
{/* ... */}
</DateInput>
<DateInput className="my-date-input">
{/* ... */}
</DateInput>;
In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using DOM attributes, which you can target in CSS selectors. These are ARIA attributes wherever possible, or data attributes when a relevant ARIA attribute does not exist. For example:
.react-aria-DateSegment[data-placeholder] {
/* ... */
}
.react-aria-DateSegment[aria-readonly] {
/* ... */
}
.react-aria-DateSegment[data-placeholder] {
/* ... */
}
.react-aria-DateSegment[aria-readonly] {
/* ... */
}
.react-aria-DateSegment[data-placeholder] {
/* ... */
}
.react-aria-DateSegment[aria-readonly] {
/* ... */
}
The className
and style
props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like Tailwind.
<DateSegment
className={({ isPlaceholder }) =>
isPlaceholder ? 'bg-gray-300' : 'bg-gray-600'}
/>;
<DateSegment
className={({ isPlaceholder }) =>
isPlaceholder ? 'bg-gray-300' : 'bg-gray-600'}
/>;
<DateSegment
className={(
{ isPlaceholder }
) =>
isPlaceholder
? 'bg-gray-300'
: 'bg-gray-600'}
/>;
Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render the placeholder as a separate element to always reserve space for it.
<DateSegment>
{({ text, placeholder, isPlaceholder }) => (
<>
<span style={{ visibility: isPlaceholder ? 'visible' : 'hidden' }}>
{placeholder}
</span>
{isPlaceholder ? '' : text}
</>
)}
</DateSegment>;
<DateSegment>
{({ text, placeholder, isPlaceholder }) => (
<>
<span
style={{
visibility: isPlaceholder ? 'visible' : 'hidden'
}}
>
{placeholder}
</span>
{isPlaceholder ? '' : text}
</>
)}
</DateSegment>;
<DateSegment>
{(
{
text,
placeholder,
isPlaceholder
}
) => (
<>
<span
style={{
visibility:
isPlaceholder
? 'visible'
: 'hidden'
}}
>
{placeholder}
</span>
{isPlaceholder
? ''
: text}
</>
)}
</DateSegment>;
The states, selectors, and render props for each component used in a DatePicker
are documented below.
DatePicker#
A DatePicker
can be targeted with the .react-aria-DatePicker
CSS selector, or by overriding with a custom className
. It provides a DatePickerState
object to its render props, which can be used to customize the className
, style
, or children
.
Label#
A Label
can be targeted with the .react-aria-Label
CSS selector, or by overriding with a custom className
.
Group#
A Group
can be targeted with the [role=group]
selector, or by adding a custom className
.
DateInput#
A DateInput
can be targeted with the .react-aria-DateInput
CSS selector, or by overriding with a custom className
.
DateSegment#
A DateSegment
can be targeted with the .react-aria-DateSegment
CSS selector, or by overriding with a custom className
. It supports the following states and render props:
Name | CSS Selector | Description |
isPlaceholder | [data-placeholder] | Whether the value is a placeholder. |
isReadOnly | [aria-readonly] | Whether the segment is read only. |
isInvalid | [aria-invalid] | Whether the date field is in an invalid state. |
type | [data-type="..."] | The type of segment. Values include literal , year , month , day , etc. |
text | — | The formatted text for the segment. |
value | — | The numeric value for the segment, if applicable. |
minValue | — | The minimum numeric value for the segment, if applicable. |
maxValue | — | The maximum numeric value for the segment, if applicable. |
placeholder | — | A placeholder string for the segment. |
Button#
A Button can be targeted with the .react-aria-Button
CSS selector, or by overriding with a custom className
. The next and previous buttons within a calendar can be targeted specifically with the [slot=previous]
and [slot=next]
selectors. Buttons support the following states:
Name | CSS Selector | Description |
isHovered | [data-hovered] | Whether the button is currently hovered with a mouse. |
isPressed | [data-pressed] | Whether the button is currently in a pressed state. |
isFocused | :focus | Whether the button is focused, either via a mouse or keyboard. |
isFocusVisible | [data-focus-visible] | Whether the button is keyboard focused. |
isDisabled | :disabled | Whether the button is disabled. |
Popover#
The Popover component can be targeted with the .react-aria-Popover
CSS selector, or by overriding with a custom className
. Note that it renders in a React Portal, so it will not appear as a descendant of the DatePicker in the DOM. It supports the following states and render props:
Name | CSS Selector | Description |
placement | [data-placement="left | right | top | bottom"] | The placement of the tooltip relative to the trigger. |
isEntering | [data-entering] | Whether the popover is currently entering. Use this to apply animations. |
isExiting | [data-exiting] | Whether the popover is currently exiting. Use this to apply animations. |
Dialog#
A Dialog can be targeted with the .react-aria-Dialog
CSS selector, or by overriding with a custom className
.
Calendar#
A Calendar can be targeted with the .react-aria-Calendar
CSS selector, or by overriding with a custom className
.
CalendarGrid#
A CalendarGrid
can be targeted with the .react-aria-CalendarGrid
CSS selector, or by overriding with a custom className
.
CalendarCell#
A CalendarCell
can be targeted with the .react-aria-CalendarCell
CSS selector, or by overriding with a custom className
. It supports the following states:
Name | CSS Selector | Description |
date | — | The date that the cell represents. |
formattedDate | — | The day number formatted according to the current locale. |
isHovered | [data-hovered] | Whether the cell is currently hovered with a mouse. |
isPressed | [data-pressed] | Whether the cell is currently being pressed. |
isSelected | [data-selected] | Whether the cell is selected. |
isSelectionStart | [data-selection-start] | Whether the cell is the first date in a range selection. |
isSelectionEnd | [data-selection-end] | Whether the cell is the last date in a range selection. |
isFocused | :focus | Whether the cell is focused. |
isFocusVisible | [data-focus-visible] | Whether the cell is keyboard focused. |
isDisabled | [data-disabled] | Whether the cell is disabled, according to the calendar's |
isOutsideVisibleRange | [data-outside-visible-range] | Whether the cell is outside the visible range of the calendar. For example, dates before the first day of a month in the same week. |
isOutsideMonth | [data-outside-month] | Whether the cell is outside the current month. |
isUnavailable | [data-unavailable] | Whether the cell is unavailable, according to the calendar's Note that because they are focusable, unavailable dates must meet a 4.5:1 color contrast ratio, as defined by WCAG. |
isInvalid | [aria-invalid] | Whether the cell is part of an invalid selection. |
Text#
The help text elements within a DatePicker
can be targeted with the [slot=description]
and [slot=errorMessage]
CSS selectors, or by adding a custom className
.
Reusable wrappers#
If you will use a DatePicker in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.
This example wraps DatePicker
and all of its children together into a single component which accepts a label
prop, which is passed to the right place. It also shows how to use the description
and errorMessage
slots to render help text (see below for details).
import {Text} from 'react-aria-components';
function MyDatePicker({label, description, errorMessage, ...props}) {
return (
<DatePicker {...props}>
<Label>{label}</Label>
<Group>
<DateInput>
{segment => <DateSegment segment={segment} />}
</DateInput>
<Button>▼</Button>
</Group>
{description && <Text slot="description">{description}</Text>}
{errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
<Popover>
<Dialog>
<Calendar>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{date => <CalendarCell date={date} />}
</CalendarGrid>
{errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
</Calendar>
</Dialog>
</Popover>
</DatePicker>
);
}
<MyDatePicker label="Event date" />
import {Text} from 'react-aria-components';
function MyDatePicker(
{ label, description, errorMessage, ...props }
) {
return (
<DatePicker {...props}>
<Label>{label}</Label>
<Group>
<DateInput>
{(segment) => <DateSegment segment={segment} />}
</DateInput>
<Button>▼</Button>
</Group>
{description && (
<Text slot="description">{description}</Text>
)}
{errorMessage && (
<Text slot="errorMessage">{errorMessage}</Text>
)}
<Popover>
<Dialog>
<Calendar>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
{errorMessage && (
<Text slot="errorMessage">
{errorMessage}
</Text>
)}
</Calendar>
</Dialog>
</Popover>
</DatePicker>
);
}
<MyDatePicker label="Event date" />
import {Text} from 'react-aria-components';
function MyDatePicker(
{
label,
description,
errorMessage,
...props
}
) {
return (
<DatePicker
{...props}
>
<Label>
{label}
</Label>
<Group>
<DateInput>
{(segment) => (
<DateSegment
segment={segment}
/>
)}
</DateInput>
<Button>
▼
</Button>
</Group>
{description && (
<Text slot="description">
{description}
</Text>
)}
{errorMessage && (
<Text slot="errorMessage">
{errorMessage}
</Text>
)}
<Popover>
<Dialog>
<Calendar>
<header>
<Button slot="previous">
◀
</Button>
<Heading />
<Button slot="next">
▶
</Button>
</header>
<CalendarGrid>
{(date) => (
<CalendarCell
date={date}
/>
)}
</CalendarGrid>
{errorMessage &&
(
<Text slot="errorMessage">
{errorMessage}
</Text>
)}
</Calendar>
</Dialog>
</Popover>
</DatePicker>
);
}
<MyDatePicker label="Event date" />
Usage#
The following examples show how to use the MyDatePicker
component created in the above example.
Value#
A DatePicker
displays a placeholder by default. An initial, uncontrolled value can be provided to the DatePicker
using the defaultValue
prop. Alternatively, a controlled value can be provided using the value
prop.
Date values are provided using objects in the @internationalized/date package. This library handles correct international date manipulation across calendars, time zones, and other localization concerns. DatePicker
supports values of the following types:
CalendarDate
– a date without any time components. May be parsed from a string representation using theparseDate
function. Use this type to represent dates where the time is not important, such as a birthday or an all day calendar event.CalendarDateTime
– a date with a time, but not in any specific time zone. May be parsed from a string representation using theparseDateTime
function. Use this type to represent times that occur at the same local time regardless of the time zone, such as the time of New Years Eve fireworks which always occur at midnight. Most times are better stored as aZonedDateTime
.ZonedDateTime
– a date with a time in a specific time zone. May be parsed from a string representation using theparseZonedDateTime
,parseAbsolute
, orparseAbsoluteToLocal
functions. Use this type to represent an exact moment in time at a particular location on Earth.
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(parseDate('2020-02-03'));
return (
<>
<MyDatePicker
label="Date (uncontrolled)"
defaultValue={parseDate('2020-02-03')} />
<MyDatePicker
label="Date (controlled)"
value={value}
onChange={setValue} />
</>
);
}
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(
parseDate('2020-02-03')
);
return (
<>
<MyDatePicker
label="Date (uncontrolled)"
defaultValue={parseDate('2020-02-03')}
/>
<MyDatePicker
label="Date (controlled)"
value={value}
onChange={setValue}
/>
</>
);
}
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] =
React.useState(
parseDate(
'2020-02-03'
)
);
return (
<>
<MyDatePicker
label="Date (uncontrolled)"
defaultValue={parseDate(
'2020-02-03'
)}
/>
<MyDatePicker
label="Date (controlled)"
value={value}
onChange={setValue}
/>
</>
);
}
Events#
DatePicker
accepts an onChange
prop which is triggered whenever the date is edited by the user. The example below uses onChange
to update a separate element with a formatted version of the date in the user's locale and local time zone. This is done by converting the date to a native JavaScript Date
object to pass to the formatter.
import {useDateFormatter} from 'react-aria';
import {getLocalTimeZone} from '@internationalized/date';
function Example() {
let [date, setDate] = React.useState(parseDate('1985-07-03'));
let formatter = useDateFormatter({ dateStyle: 'full' });
return (
<>
<MyDatePicker label="Birth date" value={date} onChange={setDate} />
<p>Selected date: {formatter.format(date.toDate(getLocalTimeZone()))}</p>
</>
);
}
import {useDateFormatter} from 'react-aria';
import {getLocalTimeZone} from '@internationalized/date';
function Example() {
let [date, setDate] = React.useState(
parseDate('1985-07-03')
);
let formatter = useDateFormatter({ dateStyle: 'full' });
return (
<>
<MyDatePicker
label="Birth date"
value={date}
onChange={setDate}
/>
<p>
Selected date:{' '}
{formatter.format(date.toDate(getLocalTimeZone()))}
</p>
</>
);
}
import {useDateFormatter} from 'react-aria';
import {getLocalTimeZone} from '@internationalized/date';
function Example() {
let [date, setDate] =
React.useState(
parseDate(
'1985-07-03'
)
);
let formatter =
useDateFormatter({
dateStyle: 'full'
});
return (
<>
<MyDatePicker
label="Birth date"
value={date}
onChange={setDate}
/>
<p>
Selected date:
{' '}
{formatter
.format(
date.toDate(
getLocalTimeZone()
)
)}
</p>
</>
);
}
Time zones#
DatePicker
is time zone aware when a ZonedDateTime
object is provided as the value. In this case, the time zone abbreviation is displayed, and time zone concerns such as daylight saving time are taken into account when the value is manipulated.
In most cases, your data will come from and be sent to a server as an ISO 8601 formatted string. @internationalized/date includes functions for parsing strings in multiple formats into ZonedDateTime
objects. Which format you use will depend on what information you need to store.
parseZonedDateTime
– This function parses a date with an explicit time zone and optional UTC offset attached (e.g."2021-11-07T00:45[America/Los_Angeles]"
or"2021-11-07T00:45-07:00[America/Los_Angeles]"
). This format preserves the maximum amount of information. If the exact local time and time zone that a user selected is important, use this format. Storing the time zone and offset that was selected rather than converting to UTC ensures that the local time is correct regardless of daylight saving rule changes (e.g. if a locale abolishes DST). Examples where this applies include calendar events, reminders, and other times that occur in a particular location.parseAbsolute
– This function parses an absolute date and time that occurs at the same instant at all locations on Earth. It can be represented in UTC (e.g."2021-11-07T07:45:00Z"
), or stored with a particular offset (e.g."2021-11-07T07:45:00-07:00"
). A time zone identifier, e.g.America/Los_Angeles
, must be passed, and the result will be converted into that time zone. Absolute times are the best way to represent events that occurred in the past, or future events where an exact time is needed, regardless of time zone.parseAbsoluteToLocal
– This function parses an absolute date and time into the current user's local time zone. It is a shortcut forparseAbsolute
, and accepts the same formats.
import {parseZonedDateTime} from '@internationalized/date';
<MyDatePicker
label="Event date"
defaultValue={parseZonedDateTime('2022-11-07T00:45[America/Los_Angeles]')}
/>
import {parseZonedDateTime} from '@internationalized/date';
<MyDatePicker
label="Event date"
defaultValue={parseZonedDateTime(
'2022-11-07T00:45[America/Los_Angeles]'
)}
/>
import {parseZonedDateTime} from '@internationalized/date';
<MyDatePicker
label="Event date"
defaultValue={parseZonedDateTime(
'2022-11-07T00:45[America/Los_Angeles]'
)}
/>
DatePicker
displays times in the time zone included in the ZonedDateTime
object. The above example is always displayed in Pacific Standard Time because the America/Los_Angeles
time zone identifier is provided. @internationalized/date includes functions for converting dates between time zones, or parsing a date directly into a specific time zone or the user's local time zone, as shown below.
import {parseAbsoluteToLocal} from '@internationalized/date';
<MyDatePicker
label="Event date"
defaultValue={parseAbsoluteToLocal('2021-11-07T07:45:00Z')}
/>
import {parseAbsoluteToLocal} from '@internationalized/date';
<MyDatePicker
label="Event date"
defaultValue={parseAbsoluteToLocal(
'2021-11-07T07:45:00Z'
)}
/>
import {parseAbsoluteToLocal} from '@internationalized/date';
<MyDatePicker
label="Event date"
defaultValue={parseAbsoluteToLocal(
'2021-11-07T07:45:00Z'
)}
/>
Granularity#
The granularity
prop allows you to control the smallest unit that is displayed by DatePicker
. By default, CalendarDate
values are displayed with "day"
granularity (year, month, and day), and CalendarDateTime
and ZonedDateTime
values are displayed with "minute"
granularity. More granular time values can be displayed by setting the granularity
prop to "second"
.
In addition, when a value with a time is provided but you wish to only display the date, you can set the granularity to "day"
. This has no effect on the actual value (it still has a time component), only on what fields are displayed. In the following example, two DatePickers are synchronized with the same value, but display different granularities.
function Example() {
let [date, setDate] = React.useState(
parseAbsoluteToLocal('2021-04-07T18:45:22Z')
);
return (
<>
<MyDatePicker
label="Date and time"
granularity="second"
value={date}
onChange={setDate}
/>
<MyDatePicker
label="Date"
granularity="day"
value={date}
onChange={setDate}
/>
</>
);
}
function Example() {
let [date, setDate] = React.useState(
parseAbsoluteToLocal('2021-04-07T18:45:22Z')
);
return (
<>
<MyDatePicker
label="Date and time"
granularity="second"
value={date}
onChange={setDate}
/>
<MyDatePicker
label="Date"
granularity="day"
value={date}
onChange={setDate}
/>
</>
);
}
function Example() {
let [date, setDate] =
React.useState(
parseAbsoluteToLocal(
'2021-04-07T18:45:22Z'
)
);
return (
<>
<MyDatePicker
label="Date and time"
granularity="second"
value={date}
onChange={setDate}
/>
<MyDatePicker
label="Date"
granularity="day"
value={date}
onChange={setDate}
/>
</>
);
}
If no value
or defaultValue
prop is passed, then the granularity
prop also affects which type of value is emitted from the onChange
event. Note that by default, time values will not have a time zone because none was supplied. You can override this by setting the placeholderValue
prop explicitly. Values emitted from onChange
will use the time zone of the placeholder value.
import {now} from '@internationalized/date';
<MyDatePicker
label="Event date"
granularity="second" />
<MyDatePicker
label="Event date"
placeholderValue={now('America/New_York')}
granularity="second" />
import {now} from '@internationalized/date';
<MyDatePicker
label="Event date"
granularity="second" />
<MyDatePicker
label="Event date"
placeholderValue={now('America/New_York')}
granularity="second" />
import {now} from '@internationalized/date';
<MyDatePicker
label="Event date"
granularity="second"
/>
<MyDatePicker
label="Event date"
placeholderValue={now(
'America/New_York'
)}
granularity="second"
/>
International calendars#
DatePicker
supports selecting dates in many calendar systems used around the world, including Gregorian, Hebrew, Indian, Islamic, Buddhist, and more. Dates are automatically displayed in the appropriate calendar system for the user's locale. The calendar system can be overridden using the Unicode calendar locale extension, passed to the I18nProvider component.
Selected dates passed to onChange
always use the same calendar system as the value
or defaultValue
prop. If no value
or defaultValue
is provided, then dates passed to onChange
are always in the Gregorian calendar since this is the most commonly used. This means that even though the user selects dates in their local calendar system, applications are able to deal with dates from all users consistently.
The below example displays a DatePicker
in the Hindi language, using the Indian calendar. Dates emitted from onChange
are in the Gregorian calendar.
import {I18nProvider} from 'react-aria';
function Example() {
let [date, setDate] = React.useState(null);
return (
<I18nProvider locale="hi-IN-u-ca-indian">
<MyDatePicker label="Date" value={date} onChange={setDate} />
<p>Selected date: {date?.toString()}</p>
</I18nProvider>
);
}
import {I18nProvider} from 'react-aria';
function Example() {
let [date, setDate] = React.useState(null);
return (
<I18nProvider locale="hi-IN-u-ca-indian">
<MyDatePicker
label="Date"
value={date}
onChange={setDate}
/>
<p>Selected date: {date?.toString()}</p>
</I18nProvider>
);
}
import {I18nProvider} from 'react-aria';
function Example() {
let [date, setDate] =
React.useState(null);
return (
<I18nProvider locale="hi-IN-u-ca-indian">
<MyDatePicker
label="Date"
value={date}
onChange={setDate}
/>
<p>
Selected date:
{' '}
{date
?.toString()}
</p>
</I18nProvider>
);
}
Minimum and maximum values#
The minValue
and maxValue
props can also be used to perform builtin validation. This prevents the user from selecting dates outside the valid range in the calendar, and marks the date field as invalid using ARIA. You should implement a visual indication that the date picker is invalid as well.
This example only accepts dates after today.
import {today} from '@internationalized/date';
<MyDatePicker
label="Appointment date"
minValue={today(getLocalTimeZone())}
defaultValue={parseDate('2022-02-03')} />
import {today} from '@internationalized/date';
<MyDatePicker
label="Appointment date"
minValue={today(getLocalTimeZone())}
defaultValue={parseDate('2022-02-03')} />
import {today} from '@internationalized/date';
<MyDatePicker
label="Appointment date"
minValue={today(
getLocalTimeZone()
)}
defaultValue={parseDate(
'2022-02-03'
)}
/>
Unavailable dates#
DatePicker
supports marking certain dates as unavailable. These dates remain focusable with the keyboard in the calendar so that navigation is consistent, but cannot be selected by the user. When an unavailable date is entered into the date field, it is marked as invalid. The isDateUnavailable
prop accepts a callback that is called to evaluate whether each visible date is unavailable.
This example includes multiple unavailable date ranges, e.g. dates when no appointments are available. In addition, all weekends are unavailable. The minValue
prop is also used to prevent selecting dates before today.
import {useLocale} from 'react-aria';
import {isWeekend, today} from '@internationalized/date';
function Example() {
let now = today(getLocalTimeZone());
let disabledRanges = [
[now, now.add({ days: 5 })],
[now.add({ days: 14 }), now.add({ days: 16 })],
[now.add({ days: 23 }), now.add({ days: 24 })]
];
let { locale } = useLocale();
let isDateUnavailable = (date) =>
isWeekend(date, locale) ||
disabledRanges.some((interval) =>
date.compare(interval[0]) >= 0 && date.compare(interval[1]) <= 0
);
return (
<MyDatePicker
label="Appointment date"
minValue={today(getLocalTimeZone())}
isDateUnavailable={isDateUnavailable}
/>
);
}
import {useLocale} from 'react-aria';
import {isWeekend, today} from '@internationalized/date';
function Example() {
let now = today(getLocalTimeZone());
let disabledRanges = [
[now, now.add({ days: 5 })],
[now.add({ days: 14 }), now.add({ days: 16 })],
[now.add({ days: 23 }), now.add({ days: 24 })]
];
let { locale } = useLocale();
let isDateUnavailable = (date) =>
isWeekend(date, locale) ||
disabledRanges.some((interval) =>
date.compare(interval[0]) >= 0 &&
date.compare(interval[1]) <= 0
);
return (
<MyDatePicker
label="Appointment date"
minValue={today(getLocalTimeZone())}
isDateUnavailable={isDateUnavailable}
/>
);
}
import {useLocale} from 'react-aria';
import {
isWeekend,
today
} from '@internationalized/date';
function Example() {
let now = today(
getLocalTimeZone()
);
let disabledRanges = [
[
now,
now.add({
days: 5
})
],
[
now.add({
days: 14
}),
now.add({
days: 16
})
],
[
now.add({
days: 23
}),
now.add({
days: 24
})
]
];
let { locale } =
useLocale();
let isDateUnavailable =
(date) =>
isWeekend(
date,
locale
) ||
disabledRanges
.some((
interval
) =>
date.compare(
interval[0]
) >= 0 &&
date.compare(
interval[1]
) <= 0
);
return (
<MyDatePicker
label="Appointment date"
minValue={today(
getLocalTimeZone()
)}
isDateUnavailable={isDateUnavailable}
/>
);
}
Help text#
The description
slot can be used to associate additional help text with a date picker. Additionally, the errorMessage
slot can be used to help the user fix a validation error. It should be combined with the validationState
prop to semantically mark the date picker as invalid for assistive technologies.
This example validates that the selected date is a weekday and not a weekend according to the current locale.
import {today, isWeekend} from '@internationalized/date';
import {useLocale} from 'react-aria';
function Example() {
let [date, setDate] = React.useState(today(getLocalTimeZone()));
let {locale} = useLocale();
let isInvalid = isWeekend(date, locale);
return (
<MyDatePicker
label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid ? 'invalid' : 'valid'}
description={isInvalid ? null : 'Select a weekday'}
errorMessage={isInvalid ? 'We are closed on weekends' : null} />
);
}
import {isWeekend, today} from '@internationalized/date';
import {useLocale} from 'react-aria';
function Example() {
let [date, setDate] = React.useState(
today(getLocalTimeZone())
);
let { locale } = useLocale();
let isInvalid = isWeekend(date, locale);
return (
<MyDatePicker
label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid ? 'invalid' : 'valid'}
description={isInvalid ? null : 'Select a weekday'}
errorMessage={isInvalid
? 'We are closed on weekends'
: null}
/>
);
}
import {
isWeekend,
today
} from '@internationalized/date';
import {useLocale} from 'react-aria';
function Example() {
let [date, setDate] =
React.useState(
today(
getLocalTimeZone()
)
);
let { locale } =
useLocale();
let isInvalid =
isWeekend(
date,
locale
);
return (
<MyDatePicker
label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid
? 'invalid'
: 'valid'}
description={isInvalid
? null
: 'Select a weekday'}
errorMessage={isInvalid
? 'We are closed on weekends'
: null}
/>
);
}
Placeholder value#
When no value is set, a placeholder is shown. The format of the placeholder is influenced by the granularity
and placeholderValue
props. placeholderValue
also controls the default values of each segment when the user first interacts with them, e.g. using the up and down arrow keys, as well as the default month shown in the calendar popover. By default, the placeholderValue
is the current date at midnight, but you can set it to a more appropriate value if needed.
import {CalendarDate} from '@internationalized/date';
<MyDatePicker
label="Birth date"
placeholderValue={new CalendarDate(1980, 1, 1)}
/>
import {CalendarDate} from '@internationalized/date';
<MyDatePicker
label="Birth date"
placeholderValue={new CalendarDate(1980, 1, 1)}
/>
import {CalendarDate} from '@internationalized/date';
<MyDatePicker
label="Birth date"
placeholderValue={new CalendarDate(
1980,
1,
1
)}
/>
Hide time zone#
When a ZonedDateTime
object is provided as the value to DatePicker
, the time zone abbreviation is displayed by default. However, if this is displayed elsewhere or implicit based on the usecase, it can be hidden using the hideTimeZone
option.
<MyDatePicker
label="Appointment time"
defaultValue={parseZonedDateTime('2022-11-07T10:45[America/Los_Angeles]')}
hideTimeZone />
<MyDatePicker
label="Appointment time"
defaultValue={parseZonedDateTime(
'2022-11-07T10:45[America/Los_Angeles]'
)}
hideTimeZone
/>
<MyDatePicker
label="Appointment time"
defaultValue={parseZonedDateTime(
'2022-11-07T10:45[America/Los_Angeles]'
)}
hideTimeZone
/>
Hour cycle#
By default, DatePicker
displays times in either 12 or 24 hour hour format depending on the user's locale. However, this can be overridden using the hourCycle
prop if needed for a specific usecase. This example forces DatePicker
to use 24-hour time, regardless of the locale.
<MyDatePicker
label="Appointment time"
granularity="minute"
hourCycle={24} />
<MyDatePicker
label="Appointment time"
granularity="minute"
hourCycle={24} />
<MyDatePicker
label="Appointment time"
granularity="minute"
hourCycle={24}
/>
Advanced customization#
Composition#
If you need to customize one of the components within a DatePicker
, such as Label
or DateSegment
, in many cases you can create a wrapper component. This lets you customize the props passed to the component.
function MyDateSegment(props) {
return <MyDateSegment {...props} className="my-date-segment" />
}
function MyDateSegment(props) {
return (
<MyDateSegment {...props} className="my-date-segment" />
);
}
function MyDateSegment(
props
) {
return (
<MyDateSegment
{...props}
className="my-date-segment"
/>
);
}
Hooks#
If you need to customize things even further, such as accessing internal state or customizing DOM structure, you can drop down to the lower
level Hook-based API. DatePicker
sends props to its child elements via public React contexts for each component. You can use this context to
implement replacements for any component, using hooks from react-aria
. This allows you to replace only the components you need to customize,
and keep using the others.
DatePicker
uses the following hooks. See the linked documentation for more details.
To replace a component used within a DatePicker
, create your own component and use the useContextProps
hook to merge the local props and ref with the ones sent via context by DatePicker
. This example shows how you could implement a custom Calendar
component that works with DatePicker
.
import {CalendarContext, useContextProps} from 'react-aria-components';
import {useCalendar} from 'react-aria';
function MyCalendar(props) {
// Merge local props and ref with props from context.
let ref = React.useRef();
[props, ref] = useContextProps(props, ref, CalendarContext);
// Call useCalendarState and useCalendar.
let state = useCalendarState({...props});
let {calendarProps} = useCalendar(props, state, ref);
// Render stuff
// ...
}
import {
CalendarContext,
useContextProps
} from 'react-aria-components';
import {useCalendar} from 'react-aria';
function MyCalendar(props) {
// Merge local props and ref with props from context.
let ref = React.useRef();
[props, ref] = useContextProps(
props,
ref,
CalendarContext
);
// Call useCalendarState and useCalendar.
let state = useCalendarState({ ...props });
let { calendarProps } = useCalendar(props, state, ref);
// Render stuff
// ...
}
import {
CalendarContext,
useContextProps
} from 'react-aria-components';
import {useCalendar} from 'react-aria';
function MyCalendar(
props
) {
// Merge local props and ref with props from context.
let ref = React
.useRef();
[props, ref] =
useContextProps(
props,
ref,
CalendarContext
);
// Call useCalendarState and useCalendar.
let state =
useCalendarState({
...props
});
let { calendarProps } =
useCalendar(
props,
state,
ref
);
// Render stuff
// ...
}
This also works the other way. If you need to customize DatePicker
itself, but want to reuse the components it contains, you can do so by providing the necessary contexts. The Provider
component is an easier way to send multiple contexts at once. You can look at the DatePicker source code for more details on how to set this up.
import {ButtonContext, CalendarContext, LabelContext, useDatePicker} from 'react-aria';
import {Provider} from 'react-aria-components';
function MyDatePicker(props) {
// ...
let ref = useRef(null);
let {
labelProps,
buttonProps,
calendarProps
// ...
} = useDatePicker({/* ... */});
return (
<Provider
values={[
[LabelContext, labelProps],
[ButtonContext, buttonProps],
[CalendarContext, calendarProps]
// ...
]}
>
{props.children}
</Provider>
);
}
import {
ButtonContext,
CalendarContext,
LabelContext,
useDatePicker
} from 'react-aria';
import {Provider} from 'react-aria-components';
function MyDatePicker(props) {
// ...
let ref = useRef(null);
let {
labelProps,
buttonProps,
calendarProps
// ...
} = useDatePicker({/* ... */});
return (
<Provider
values={[
[LabelContext, labelProps],
[ButtonContext, buttonProps],
[CalendarContext, calendarProps]
// ...
]}
>
{props.children}
</Provider>
);
}
import {
ButtonContext,
CalendarContext,
LabelContext,
useDatePicker
} from 'react-aria';
import {Provider} from 'react-aria-components';
function MyDatePicker(
props
) {
// ...
let ref = useRef(null);
let {
labelProps,
buttonProps,
calendarProps
// ...
} = useDatePicker({
/* ... */
});
return (
<Provider
values={[
[
LabelContext,
labelProps
],
[
ButtonContext,
buttonProps
],
[
CalendarContext,
calendarProps
]
// ...
]}
>
{props.children}
</Provider>
);
}