DateField
A date field allows users to enter and edit date and time values using a keyboard. Each part of a date value is displayed in an individually editable segment.
install | yarn add react-aria-components |
---|---|
version | 1.0.0-alpha.0 |
usage | import {DateField} from 'react-aria-components' |
Example#
import {DateField, Label, DateInput, DateSegment} from 'react-aria-components';
<DateField>
<Label>Birth date</Label>
<DateInput>
{segment => <DateSegment segment={segment} />}
</DateInput>
</DateField>
import {
DateField,
DateInput,
DateSegment,
Label
} from 'react-aria-components';
<DateField>
<Label>Birth date</Label>
<DateInput>
{(segment) => <DateSegment segment={segment} />}
</DateInput>
</DateField>
import {
DateField,
DateInput,
DateSegment,
Label
} from 'react-aria-components';
<DateField>
<Label>
Birth date
</Label>
<DateInput>
{(segment) => (
<DateSegment
segment={segment}
/>
)}
</DateInput>
</DateField>
Show CSS
.react-aria-DateInput {
--field-border: var(--spectrum-global-color-gray-400);
--field-background: var(--spectrum-global-color-gray-50);
--text-color: var(--spectrum-alias-text-color);
--text-color-placeholder: var(--spectrum-global-color-gray-700);
--text-color-invalid: var(--spectrum-global-color-red-600);
--highlight-background: slateblue;
--highlight-foreground: white;
--highlight-background-invalid: var(--spectrum-global-color-static-red-600);
display: flex;
padding: 4px;
border: 1px solid var(--field-border);
border-radius: 6px;
background: var(--field-background);
width: fit-content;
min-width: 150px;
white-space: nowrap;
&:focus-within {
border-color: var(--highlight-background);
box-shadow: 0 0 0 1px var(--highlight-background);
}
}
.react-aria-DateSegment {
padding: 0 2px;
font-variant-numeric: tabular-nums;
text-align: end;
color: var(--text-color);
&[data-type=literal] {
padding: 0;
}
&[data-placeholder] {
color: var(--text-color-placeholder);
font-style: italic;
}
&:focus {
color: var(--highlight-foreground);
background: var(--highlight-background);
outline: none;
border-radius: 4px;
caret-color: transparent;
}
&[aria-invalid] {
color: var(--text-color-invalid);
&:focus {
background: var(--highlight-background-invalid);
color: var(--highlight-foreground);
}
}
}
.react-aria-DateField {
--text-color-invalid: var(--spectrum-global-color-red-600);
[slot=description] {
font-size: 12px;
}
[slot=errorMessage] {
font-size: 12px;
color: var(--text-color-invalid);
}
}
@media (forced-colors: active) {
.react-aria-DateField {
--text-color-invalid: LinkText;
}
.react-aria-DateInput {
forced-color-adjust: none;
--field-border: ButtonBorder;
--field-background: Field;
--text-color: FieldText;
--text-color-placeholder: FieldText;
--text-color-invalid: LinkText;
--highlight-background: Highlight;
--highlight-foreground: HighlightText;
--highlight-background-invalid: LinkText;
}
}
.react-aria-DateInput {
--field-border: var(--spectrum-global-color-gray-400);
--field-background: var(--spectrum-global-color-gray-50);
--text-color: var(--spectrum-alias-text-color);
--text-color-placeholder: var(--spectrum-global-color-gray-700);
--text-color-invalid: var(--spectrum-global-color-red-600);
--highlight-background: slateblue;
--highlight-foreground: white;
--highlight-background-invalid: var(--spectrum-global-color-static-red-600);
display: flex;
padding: 4px;
border: 1px solid var(--field-border);
border-radius: 6px;
background: var(--field-background);
width: fit-content;
min-width: 150px;
white-space: nowrap;
&:focus-within {
border-color: var(--highlight-background);
box-shadow: 0 0 0 1px var(--highlight-background);
}
}
.react-aria-DateSegment {
padding: 0 2px;
font-variant-numeric: tabular-nums;
text-align: end;
color: var(--text-color);
&[data-type=literal] {
padding: 0;
}
&[data-placeholder] {
color: var(--text-color-placeholder);
font-style: italic;
}
&:focus {
color: var(--highlight-foreground);
background: var(--highlight-background);
outline: none;
border-radius: 4px;
caret-color: transparent;
}
&[aria-invalid] {
color: var(--text-color-invalid);
&:focus {
background: var(--highlight-background-invalid);
color: var(--highlight-foreground);
}
}
}
.react-aria-DateField {
--text-color-invalid: var(--spectrum-global-color-red-600);
[slot=description] {
font-size: 12px;
}
[slot=errorMessage] {
font-size: 12px;
color: var(--text-color-invalid);
}
}
@media (forced-colors: active) {
.react-aria-DateField {
--text-color-invalid: LinkText;
}
.react-aria-DateInput {
forced-color-adjust: none;
--field-border: ButtonBorder;
--field-background: Field;
--text-color: FieldText;
--text-color-placeholder: FieldText;
--text-color-invalid: LinkText;
--highlight-background: Highlight;
--highlight-foreground: HighlightText;
--highlight-background-invalid: LinkText;
}
}
.react-aria-DateInput {
--field-border: var(--spectrum-global-color-gray-400);
--field-background: var(--spectrum-global-color-gray-50);
--text-color: var(--spectrum-alias-text-color);
--text-color-placeholder: var(--spectrum-global-color-gray-700);
--text-color-invalid: var(--spectrum-global-color-red-600);
--highlight-background: slateblue;
--highlight-foreground: white;
--highlight-background-invalid: var(--spectrum-global-color-static-red-600);
display: flex;
padding: 4px;
border: 1px solid var(--field-border);
border-radius: 6px;
background: var(--field-background);
width: fit-content;
min-width: 150px;
white-space: nowrap;
&:focus-within {
border-color: var(--highlight-background);
box-shadow: 0 0 0 1px var(--highlight-background);
}
}
.react-aria-DateSegment {
padding: 0 2px;
font-variant-numeric: tabular-nums;
text-align: end;
color: var(--text-color);
&[data-type=literal] {
padding: 0;
}
&[data-placeholder] {
color: var(--text-color-placeholder);
font-style: italic;
}
&:focus {
color: var(--highlight-foreground);
background: var(--highlight-background);
outline: none;
border-radius: 4px;
caret-color: transparent;
}
&[aria-invalid] {
color: var(--text-color-invalid);
&:focus {
background: var(--highlight-background-invalid);
color: var(--highlight-foreground);
}
}
}
.react-aria-DateField {
--text-color-invalid: var(--spectrum-global-color-red-600);
[slot=description] {
font-size: 12px;
}
[slot=errorMessage] {
font-size: 12px;
color: var(--text-color-invalid);
}
}
@media (forced-colors: active) {
.react-aria-DateField {
--text-color-invalid: LinkText;
}
.react-aria-DateInput {
forced-color-adjust: none;
--field-border: ButtonBorder;
--field-background: Field;
--text-color: FieldText;
--text-color-placeholder: FieldText;
--text-color-invalid: LinkText;
--highlight-background: Highlight;
--highlight-foreground: HighlightText;
--highlight-background-invalid: LinkText;
}
}
Features#
A date field 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. DateField
helps achieve accessible and international date and time fields 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.
- 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 DateField
.
Anatomy#
A date field consists of a label, and a group of segments representing each unit of a date and time (e.g. years, months, days, etc.). Each segment is individually focusable and editable by the user, by typing or using the arrow keys to increment and decrement the value. This approach allows values to be formatted and parsed correctly regardless of the locale or date format, and offers an easy and error-free way to edit dates using the keyboard.
DateField
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 field 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 TimeField, so you can reuse many components between them if you have both.
Concepts#
DateField
makes use of the following concepts:
Composed components#
A DateField
uses the following components, which may also be used standalone or reused in other components.
Props#
DateField#
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 | null | — | The current value (controlled). |
defaultValue | DateValue | null | — | The default value (uncontrolled). |
children | ReactNode | (
(values: DateFieldState
)) => ReactNode | — | The children of the component. A function may be provided to alter the children based on component state. |
className | string | (
(values: DateFieldState
)) => string | — | The CSS className for the element. A function may be provided to compute the class based on component state. |
style | CSSProperties | (
(values: DateFieldState
)) => CSSProperties | — | The inline style for the element. A function may be provided to compute the style based on component state. |
Events
Name | Type | Default | Description |
onFocus | (
(e: FocusEvent<Target>
)) => void | — | Handler that is called when the element receives focus. |
onBlur | (
(e: FocusEvent<Target>
)) => 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. |
Layout
Name | Type | Default | Description |
slot | string | — | A slot name for the component. Slots allow the component to receive props from a parent component. |
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.
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 | (
(values: DateInputRenderProps
)) => string | — | The CSS className for the element. A function may be provided to compute the class based on component state. |
style | CSSProperties | (
(values: DateInputRenderProps
)) => CSSProperties | — | The inline style for the element. A function may be provided to compute the style based on component state. |
Layout
Name | Type | Default | Description |
slot | string | — | A slot name for the component. Slots allow the component to receive props from a parent component. |
DateSegment#
The <DateSegment>
component renders an individual segment.
Show props
Name | Type | Default | Description |
segment | DateSegment | — | |
children | ReactNode | (
(values: DateSegmentRenderProps
)) => ReactNode | — | The children of the component. A function may be provided to alter the children based on component state. |
className | string | (
(values: DateSegmentRenderProps
)) => string | — | The CSS className for the element. A function may be provided to compute the class based on component state. |
style | CSSProperties | (
(values: DateSegmentRenderProps
)) => CSSProperties | — | The inline style for the element. A function may be provided to compute the style based on component state. |
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-DateField {
/* ... */
}
.react-aria-DateField {
/* ... */
}
.react-aria-DateField {
/* ... */
}
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 DateField
are documented below.
DateField#
A DateField
can be targeted with the .react-aria-DateField
CSS selector, or by overriding with a custom className
. It provides a DateFieldState
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
.
DateInput#
A DateInput
can be targeted with the .react-aria-DateInput
CSS selector, or by overriding with a custom className
. It supports the following states:
Name | CSS Selector | Description |
isHovered | [data-hovered] | Whether the date input is currently hovered with a mouse. |
isFocusWithin | :focus-within | Whether an element within the date input is focused, either via a mouse or keyboard. |
isFocusVisible | [data-focus-visible] | Whether an element within the date input is keyboard focused. |
isDisabled | [data-disabled] | Whether the date input is disabled. |
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. |
placeholder | — | A placeholder string for the segment. |
Text#
The help text elements within a DateField
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 DateField 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 DateField
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 type {DateFieldProps, DateValue} from 'react-aria-components';
import {Text} from 'react-aria-components';
interface MyDateFieldProps<T extends DateValue> extends DateFieldProps<T> {
label?: string;
description?: string;
errorMessage?: string;
}
function MyDateField<T extends DateValue>(
{ label, description, errorMessage, ...props }: MyDateFieldProps<T>
) {
return (
<DateField {...props}>
<Label>{label}</Label>
<DateInput>
{(segment) => <DateSegment segment={segment} />}
</DateInput>
{description && <Text slot="description">{description}</Text>}
{errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
</DateField>
);
}
<MyDateField label="Event date" />
import type {
DateFieldProps,
DateValue
} from 'react-aria-components';
import {Text} from 'react-aria-components';
interface MyDateFieldProps<T extends DateValue>
extends DateFieldProps<T> {
label?: string;
description?: string;
errorMessage?: string;
}
function MyDateField<T extends DateValue>(
{ label, description, errorMessage, ...props }:
MyDateFieldProps<T>
) {
return (
<DateField {...props}>
<Label>{label}</Label>
<DateInput>
{(segment) => <DateSegment segment={segment} />}
</DateInput>
{description && (
<Text slot="description">{description}</Text>
)}
{errorMessage && (
<Text slot="errorMessage">{errorMessage}</Text>
)}
</DateField>
);
}
<MyDateField label="Event date" />
import type {
DateFieldProps,
DateValue
} from 'react-aria-components';
import {Text} from 'react-aria-components';
interface MyDateFieldProps<
T extends DateValue
> extends
DateFieldProps<T> {
label?: string;
description?: string;
errorMessage?: string;
}
function MyDateField<
T extends DateValue
>(
{
label,
description,
errorMessage,
...props
}: MyDateFieldProps<T>
) {
return (
<DateField
{...props}
>
<Label>
{label}
</Label>
<DateInput>
{(segment) => (
<DateSegment
segment={segment}
/>
)}
</DateInput>
{description && (
<Text slot="description">
{description}
</Text>
)}
{errorMessage && (
<Text slot="errorMessage">
{errorMessage}
</Text>
)}
</DateField>
);
}
<MyDateField label="Event date" />
Usage#
The following examples show how to use the MyDateField
component created in the above example.
Value#
A DateField
displays a placeholder by default. An initial, uncontrolled value can be provided to the DateField
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. DateField
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 (
<>
<MyDateField
label="Date (uncontrolled)"
defaultValue={parseDate('2020-02-03')} />
<MyDateField
label="Date (controlled)"
value={value}
onChange={setValue} />
</>
);
}
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(
parseDate('2020-02-03')
);
return (
<>
<MyDateField
label="Date (uncontrolled)"
defaultValue={parseDate('2020-02-03')}
/>
<MyDateField
label="Date (controlled)"
value={value}
onChange={setValue}
/>
</>
);
}
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] =
React.useState(
parseDate(
'2020-02-03'
)
);
return (
<>
<MyDateField
label="Date (uncontrolled)"
defaultValue={parseDate(
'2020-02-03'
)}
/>
<MyDateField
label="Date (controlled)"
value={value}
onChange={setValue}
/>
</>
);
}
Events#
DateField
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 {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@react-aria/i18n';
function Example() {
let [date, setDate] = React.useState(parseDate('1985-07-03'));
let formatter = useDateFormatter({dateStyle: 'full'});
return (
<>
<MyDateField label="Birth date" value={date} onChange={setDate} />
<p>Selected date: {formatter.format(date.toDate(getLocalTimeZone()))}</p>
</>
);
}
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@react-aria/i18n';
function Example() {
let [date, setDate] = React.useState(
parseDate('1985-07-03')
);
let formatter = useDateFormatter({ dateStyle: 'full' });
return (
<>
<MyDateField
label="Birth date"
value={date}
onChange={setDate}
/>
<p>
Selected date:{' '}
{formatter.format(date.toDate(getLocalTimeZone()))}
</p>
</>
);
}
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@react-aria/i18n';
function Example() {
let [date, setDate] =
React.useState(
parseDate(
'1985-07-03'
)
);
let formatter =
useDateFormatter({
dateStyle: 'full'
});
return (
<>
<MyDateField
label="Birth date"
value={date}
onChange={setDate}
/>
<p>
Selected date:
{' '}
{formatter
.format(
date.toDate(
getLocalTimeZone()
)
)}
</p>
</>
);
}
Time zones#
DateField
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';
<MyDateField
label="Event date"
defaultValue={parseZonedDateTime('2022-11-07T00:45[America/Los_Angeles]')}
/>
import {parseZonedDateTime} from '@internationalized/date';
<MyDateField
label="Event date"
defaultValue={parseZonedDateTime(
'2022-11-07T00:45[America/Los_Angeles]'
)}
/>
import {parseZonedDateTime} from '@internationalized/date';
<MyDateField
label="Event date"
defaultValue={parseZonedDateTime(
'2022-11-07T00:45[America/Los_Angeles]'
)}
/>
DateField
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';
<MyDateField
label="Event date"
defaultValue={parseAbsoluteToLocal('2021-11-07T07:45:00Z')}
/>
import {parseAbsoluteToLocal} from '@internationalized/date';
<MyDateField
label="Event date"
defaultValue={parseAbsoluteToLocal(
'2021-11-07T07:45:00Z'
)}
/>
import {parseAbsoluteToLocal} from '@internationalized/date';
<MyDateField
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 DateField
. 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 DateFields are synchronized with the same value, but display different granularities.
function Example() {
let [date, setDate] = React.useState(
parseAbsoluteToLocal('2021-04-07T18:45:22Z')
);
return (
<>
<MyDateField
label="Date and time"
granularity="second"
value={date}
onChange={setDate}
/>
<MyDateField
label="Date"
granularity="day"
value={date}
onChange={setDate}
/>
</>
);
}
function Example() {
let [date, setDate] = React.useState(
parseAbsoluteToLocal('2021-04-07T18:45:22Z')
);
return (
<>
<MyDateField
label="Date and time"
granularity="second"
value={date}
onChange={setDate}
/>
<MyDateField
label="Date"
granularity="day"
value={date}
onChange={setDate}
/>
</>
);
}
function Example() {
let [date, setDate] =
React.useState(
parseAbsoluteToLocal(
'2021-04-07T18:45:22Z'
)
);
return (
<>
<MyDateField
label="Date and time"
granularity="second"
value={date}
onChange={setDate}
/>
<MyDateField
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';
<MyDateField
label="Event date"
granularity="second" />
<MyDateField
label="Event date"
placeholderValue={now('America/New_York')}
granularity="second" />
import {now} from '@internationalized/date';
<MyDateField
label="Event date"
granularity="second" />
<MyDateField
label="Event date"
placeholderValue={now('America/New_York')}
granularity="second" />
import {now} from '@internationalized/date';
<MyDateField
label="Event date"
granularity="second"
/>
<MyDateField
label="Event date"
placeholderValue={now(
'America/New_York'
)}
granularity="second"
/>
International calendars#
DateField
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 DateField
in the Hindi language, using the Indian calendar. Dates emitted from onChange
are in the Gregorian calendar.
import {I18nProvider} from '@react-aria/i18n';
function Example() {
let [date, setDate] = React.useState<DateValue | null>(null);
return (
<I18nProvider locale="hi-IN-u-ca-indian">
<MyDateField label="Date" value={date} onChange={setDate} />
<p>Selected date: {date?.toString()}</p>
</I18nProvider>
);
}
import {I18nProvider} from '@react-aria/i18n';
function Example() {
let [date, setDate] = React.useState<DateValue | null>(
null
);
return (
<I18nProvider locale="hi-IN-u-ca-indian">
<MyDateField
label="Date"
value={date}
onChange={setDate}
/>
<p>Selected date: {date?.toString()}</p>
</I18nProvider>
);
}
import {I18nProvider} from '@react-aria/i18n';
function Example() {
let [date, setDate] =
React.useState<
DateValue | null
>(null);
return (
<I18nProvider locale="hi-IN-u-ca-indian">
<MyDateField
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 marks the date field as invalid using ARIA if the user enters an invalid date. You should implement a visual indication that the date field is invalid as well.
This example only accepts dates after today.
import {today} from '@internationalized/date';
<MyDateField
label="Appointment date"
minValue={today(getLocalTimeZone())}
defaultValue={parseDate('2022-02-03')} />
import {today} from '@internationalized/date';
<MyDateField
label="Appointment date"
minValue={today(getLocalTimeZone())}
defaultValue={parseDate('2022-02-03')} />
import {today} from '@internationalized/date';
<MyDateField
label="Appointment date"
minValue={today(
getLocalTimeZone()
)}
defaultValue={parseDate(
'2022-02-03'
)}
/>
Help text#
The description
slot can be used to associate additional help text with a date field. 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 field 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 (
<MyDateField
label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid ? 'invalid' : 'valid'}
description={isInvalid ? undefined : 'Select a weekday'}
errorMessage={isInvalid ? 'We are closed on weekends' : undefined} />
);
}
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 (
<MyDateField
label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid ? 'invalid' : 'valid'}
description={isInvalid
? undefined
: 'Select a weekday'}
errorMessage={isInvalid
? 'We are closed on weekends'
: undefined}
/>
);
}
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 (
<MyDateField
label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid
? 'invalid'
: 'valid'}
description={isInvalid
? undefined
: 'Select a weekday'}
errorMessage={isInvalid
? 'We are closed on weekends'
: undefined}
/>
);
}
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. 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';
<MyDateField
label="Birth date"
placeholderValue={new CalendarDate(1980, 1, 1)}
/>
import {CalendarDate} from '@internationalized/date';
<MyDateField
label="Birth date"
placeholderValue={new CalendarDate(1980, 1, 1)}
/>
import {CalendarDate} from '@internationalized/date';
<MyDateField
label="Birth date"
placeholderValue={new CalendarDate(
1980,
1,
1
)}
/>
Hide time zone#
When a ZonedDateTime
object is provided as the value to DateField
, 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.
<MyDateField
label="Appointment time"
defaultValue={parseZonedDateTime('2022-11-07T10:45[America/Los_Angeles]')}
hideTimeZone />
<MyDateField
label="Appointment time"
defaultValue={parseZonedDateTime(
'2022-11-07T10:45[America/Los_Angeles]'
)}
hideTimeZone
/>
<MyDateField
label="Appointment time"
defaultValue={parseZonedDateTime(
'2022-11-07T10:45[America/Los_Angeles]'
)}
hideTimeZone
/>
Hour cycle#
By default, DateField
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 DateField
to use 24-hour time, regardless of the locale.
<MyDateField
label="Appointment time"
granularity="minute"
hourCycle={24} />
<MyDateField
label="Appointment time"
granularity="minute"
hourCycle={24} />
<MyDateField
label="Appointment time"
granularity="minute"
hourCycle={24}
/>
Advanced customization#
Composition#
If you need to customize one of the components within a DateField
, 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. See useDateField for more details.