Calendar
A calendar displays one or more date grids and allows users to select a single date.
install | yarn add react-aria-components |
---|---|
version | 3.17.0 |
usage | import {Calendar} from 'react-aria-components' |
Example#
import {Button, Calendar, CalendarCell, CalendarGrid, Heading} from 'react-aria-components';
<Calendar aria-label="Appointment date">
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
</Calendar>
import {
Button,
Calendar,
CalendarCell,
CalendarGrid,
Heading
} from 'react-aria-components';
<Calendar aria-label="Appointment date">
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
</Calendar>
import {
Button,
Calendar,
CalendarCell,
CalendarGrid,
Heading
} from 'react-aria-components';
<Calendar aria-label="Appointment date">
<header>
<Button slot="previous">
◀
</Button>
<Heading />
<Button slot="next">
▶
</Button>
</header>
<CalendarGrid>
{(date) => (
<CalendarCell
date={date}
/>
)}
</CalendarGrid>
</Calendar>
Show CSS
.react-aria-Calendar {
width: fit-content;
& 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(--spectrum-alias-background-color-default);
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-Calendar {
width: fit-content;
& 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(--spectrum-alias-background-color-default);
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-Calendar {
width: fit-content;
& 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(--spectrum-alias-background-color-default);
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#
There is no standalone calendar element in HTML. <input type="date">
is close, but this is very limited in functionality, lacking in internationalization capabilities, inconsistent between browsers, and difficult to style. Calendar
helps achieve accessible and international calendar components that can be styled as needed.
- Flexible – Display one or more months at once, or a custom time range for use cases like a week view. Minimum and maximum values, unavailable dates, and non-contiguous selections are supported as well.
- International – Support for 13 calendar systems used around the world, including Gregorian, Buddhist, Islamic, Persian, and more. Locale-specific formatting, number systems, and right-to-left support are available as well.
- Accessible – Calendar cells can be navigated and selected using the keyboard, and localized screen reader messages are included to announce when the selection and visible date range change.
- 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 Calendar
.
Anatomy#
A calendar consists of a grouping element containing one or more date grids (e.g. months), and a previous and next button for navigating between date ranges. Each calendar grid consists of cells containing button elements that can be pressed and navigated to using the arrow keys to select a date.
Calendar
also supports an optional error message element, which can be used to provide more context about any validation errors. This is linked with the calendar via the aria-describedby
attribute.
Note that much of this anatomy is shared with range calendars. If you have both, the styling and internal components such as CalendarCell
can be shared.
Concepts#
Calendar
makes use of the following concepts:
Composed components#
A Calendar
uses the following components, which may also be used standalone or reused in other components.
Props#
Calendar#
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. |
Heading#
A <Heading>
accepts all HTML attributes.
Button#
A <Button>
accepts its contents as children
. Other props such as onPress
and isDisabled
will be set by the 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. |
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-Calendar {
/* ... */
}
.react-aria-Calendar {
/* ... */
}
.react-aria-Calendar {
/* ... */
}
A custom className
can also be specified on any component. This overrides the default className
provided by React Aria with your own.
<CalendarGrid className="my-calendar-grid">
{/* ... */}
</CalendarGrid>
<CalendarGrid className="my-calendar-grid">
{/* ... */}
</CalendarGrid>
<CalendarGrid className="my-calendar-grid">
{/* ... */}
</CalendarGrid>;
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-CalendarCell[data-selected] {
/* ... */
}
.react-aria-CalendarCell[aria-invalid] {
/* ... */
}
.react-aria-CalendarCell[data-selected] {
/* ... */
}
.react-aria-CalendarCell[aria-invalid] {
/* ... */
}
.react-aria-CalendarCell[data-selected] {
/* ... */
}
.react-aria-CalendarCell[aria-invalid] {
/* ... */
}
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.
<CalendarCell
className={({ isSelected }) => isSelected ? 'bg-blue-600' : 'bg-gray-600'}
/>;
<CalendarCell
className={({ isSelected }) =>
isSelected ? 'bg-blue-600' : 'bg-gray-600'}
/>;
<CalendarCell
className={(
{ isSelected }
) =>
isSelected
? 'bg-blue-600'
: '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 add an additional element when a date is unavailable.
<CalendarCell>
{({formattedDate, isUnavailable}) => (
<>
{isUnavailable && <UnavailableIcon />}
<span>{formattedDate}</span>
</>
)}
</CalendarCell>
<CalendarCell>
{({formattedDate, isUnavailable}) => (
<>
{isUnavailable && <UnavailableIcon />}
<span>{formattedDate}</span>
</>
)}
</CalendarCell>
<CalendarCell>
{(
{
formattedDate,
isUnavailable
}
) => (
<>
{isUnavailable && (
<UnavailableIcon />
)}
<span>
{formattedDate}
</span>
</>
)}
</CalendarCell>;
The states, selectors, and render props for each component used in a Calendar
are documented below.
Calendar#
A Calendar
can be targeted with the .react-aria-Calendar
CSS selector, or by overriding with a custom className
. It provides a CalendarState
object to its render props, which can be used to customize the className
, style
, or children
.
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 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. |
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 error message element within a Calendar
can be targeted with the [slot=errorMessage]
CSS selector, or by adding a custom className
.
Multi-month#
Multiple CalendarGrid
elements can be rendered to show multiple months at once. The visibleDuration
prop should be provided to the Calendar
component to specify how many months are visible, and each CalendarGrid
accepts an offset
prop to specify its starting date relative to the first visible date.
<Calendar aria-label="Appointment date" visibleDuration={{months: 2}}>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<div style={{display: 'flex', gap: 30}}>
<CalendarGrid>
{date => <CalendarCell date={date} />}
</CalendarGrid>
<CalendarGrid offset={{months: 1}}>
{date => <CalendarCell date={date} />}
</CalendarGrid>
</div>
</Calendar>
<Calendar
aria-label="Appointment date"
visibleDuration={{ months: 2 }}
>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<div style={{ display: 'flex', gap: 30 }}>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
<CalendarGrid offset={{ months: 1 }}>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
</div>
</Calendar>
<Calendar
aria-label="Appointment date"
visibleDuration={{
months: 2
}}
>
<header>
<Button slot="previous">
◀
</Button>
<Heading />
<Button slot="next">
▶
</Button>
</header>
<div
style={{
display: 'flex',
gap: 30
}}
>
<CalendarGrid>
{(date) => (
<CalendarCell
date={date}
/>
)}
</CalendarGrid>
<CalendarGrid
offset={{
months: 1
}}
>
{(date) => (
<CalendarCell
date={date}
/>
)}
</CalendarGrid>
</div>
</Calendar>
Reusable wrappers#
If you will use a Calendar 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 also shows how to use the errorMessage
slot to render help text in case of a validation error (see below for details).
import {Text} from 'react-aria-components';
function MyCalendar({errorMessage, ...props}) {
return (
<Calendar {...props}>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{date => <CalendarCell date={date} />}
</CalendarGrid>
{errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
</Calendar>
);
}
<MyCalendar aria-label="Event date" />
import {Text} from 'react-aria-components';
function MyCalendar({ errorMessage, ...props }) {
return (
<Calendar {...props}>
<header>
<Button slot="previous">◀</Button>
<Heading />
<Button slot="next">▶</Button>
</header>
<CalendarGrid>
{(date) => <CalendarCell date={date} />}
</CalendarGrid>
{errorMessage && (
<Text slot="errorMessage">{errorMessage}</Text>
)}
</Calendar>
);
}
<MyCalendar aria-label="Event date" />
import {Text} from 'react-aria-components';
function MyCalendar(
{
errorMessage,
...props
}
) {
return (
<Calendar {...props}>
<header>
<Button slot="previous">
◀
</Button>
<Heading />
<Button slot="next">
▶
</Button>
</header>
<CalendarGrid>
{(date) => (
<CalendarCell
date={date}
/>
)}
</CalendarGrid>
{errorMessage && (
<Text slot="errorMessage">
{errorMessage}
</Text>
)}
</Calendar>
);
}
<MyCalendar aria-label="Event date" />
Usage#
The following examples show how to use the MyCalendar
component created in the above example.
Value#
A Calendar
has no selection by default. An initial, uncontrolled value can be provided to the Calendar
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.
Calendar
supports values with both date and time components, but only allows users to modify the date. By default, Calendar
will emit CalendarDate
objects in the onChange
event, but if a CalendarDateTime
or ZonedDateTime
object is passed as the value
or defaultValue
, values of that type will be emitted, changing only the date and preserving the time components.
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(parseDate('2020-02-03'));
return (
<div style={{display: 'flex', gap: 20, flexWrap: 'wrap'}}>
<MyCalendar
aria-label="Date (uncontrolled)"
defaultValue={parseDate('2020-02-03')} />
<MyCalendar
aria-label="Date (controlled)"
value={value}
onChange={setValue} />
</div>
);
}
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] = React.useState(
parseDate('2020-02-03')
);
return (
<div
style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}
>
<MyCalendar
aria-label="Date (uncontrolled)"
defaultValue={parseDate('2020-02-03')}
/>
<MyCalendar
aria-label="Date (controlled)"
value={value}
onChange={setValue}
/>
</div>
);
}
import {parseDate} from '@internationalized/date';
function Example() {
let [value, setValue] =
React.useState(
parseDate(
'2020-02-03'
)
);
return (
<div
style={{
display: 'flex',
gap: 20,
flexWrap: 'wrap'
}}
>
<MyCalendar
aria-label="Date (uncontrolled)"
defaultValue={parseDate(
'2020-02-03'
)}
/>
<MyCalendar
aria-label="Date (controlled)"
value={value}
onChange={setValue}
/>
</div>
);
}
Events#
Calendar
accepts an onChange
prop which is triggered whenever a date is selected 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. 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('2022-07-04'));
let formatter = useDateFormatter({ dateStyle: 'full' });
return (
<>
<MyCalendar aria-label="Event 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('2022-07-04')
);
let formatter = useDateFormatter({ dateStyle: 'full' });
return (
<>
<MyCalendar
aria-label="Event 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(
'2022-07-04'
)
);
let formatter =
useDateFormatter({
dateStyle: 'full'
});
return (
<>
<MyCalendar
aria-label="Event date"
value={date}
onChange={setDate}
/>
<p>
Selected date:
{' '}
{formatter
.format(
date.toDate(
getLocalTimeZone()
)
)}
</p>
</>
);
}
International calendars#
Calendar
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 Calendar
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">
<MyCalendar aria-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">
<MyCalendar
aria-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">
<MyCalendar
aria-label="Date"
value={date}
onChange={setDate}
/>
<p>
Selected date:
{' '}
{date
?.toString()}
</p>
</I18nProvider>
);
}
Validation#
By default, Calendar
allows selecting any date. The minValue
and maxValue
props can also be used to prevent the user from selecting dates outside a certain range.
This example only accepts dates after today.
import {today} from '@internationalized/date';
<MyCalendar
aria-label="Appointment date"
minValue={today(getLocalTimeZone())}
/>
import {today} from '@internationalized/date';
<MyCalendar
aria-label="Appointment date"
minValue={today(getLocalTimeZone())}
/>
import {today} from '@internationalized/date';
<MyCalendar
aria-label="Appointment date"
minValue={today(
getLocalTimeZone()
)}
/>
Unavailable dates#
Calendar
supports marking certain dates as unavailable. These dates remain focusable with the keyboard so that navigation is consistent, but cannot be selected by the user. In this example, they are displayed in red. 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 (
<MyCalendar
aria-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 (
<MyCalendar
aria-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 (
<MyCalendar
aria-label="Appointment date"
minValue={today(
getLocalTimeZone()
)}
isDateUnavailable={isDateUnavailable}
/>
);
}
Controlling the focused date#
By default, the selected date is focused when a Calendar
first mounts. If no value
or defaultValue
prop is provided, then the current date is focused. However, Calendar
supports controlling which date is focused using the focusedValue
and onFocusChange
props. This also determines which month is visible. The defaultFocusedValue
prop allows setting the initial focused date when the Calendar
first mounts, without controlling it.
This example focuses July 1, 2021 by default. The user may change the focused date, and the onFocusChange
event updates the state. Clicking the button resets the focused date back to the initial value.
import {CalendarDate} from '@internationalized/date';
function Example() {
let defaultDate = new CalendarDate(2021, 7, 1);
let [focusedDate, setFocusedDate] = React.useState(defaultDate);
return (
<div style={{ flexDirection: 'column', alignItems: 'start', gap: 20 }}>
<button onClick={() => setFocusedDate(defaultDate)}>
Reset focused date
</button>
<MyCalendar focusedValue={focusedDate} onFocusChange={setFocusedDate} />
</div>
);
}
import {CalendarDate} from '@internationalized/date';
function Example() {
let defaultDate = new CalendarDate(2021, 7, 1);
let [focusedDate, setFocusedDate] = React.useState(
defaultDate
);
return (
<div
style={{
flexDirection: 'column',
alignItems: 'start',
gap: 20
}}
>
<button onClick={() => setFocusedDate(defaultDate)}>
Reset focused date
</button>
<MyCalendar
focusedValue={focusedDate}
onFocusChange={setFocusedDate}
/>
</div>
);
}
import {CalendarDate} from '@internationalized/date';
function Example() {
let defaultDate =
new CalendarDate(
2021,
7,
1
);
let [
focusedDate,
setFocusedDate
] = React.useState(
defaultDate
);
return (
<div
style={{
flexDirection:
'column',
alignItems:
'start',
gap: 20
}}
>
<button
onClick={() =>
setFocusedDate(
defaultDate
)}
>
Reset focused
date
</button>
<MyCalendar
focusedValue={focusedDate}
onFocusChange={setFocusedDate}
/>
</div>
);
}
Disabled#
The isDisabled
boolean prop makes the Calendar disabled. Cells cannot be focused or selected.
<MyCalendar aria-label="Event date" isDisabled />
<MyCalendar aria-label="Event date" isDisabled />
<MyCalendar
aria-label="Event date"
isDisabled
/>
Read only#
The isReadOnly
boolean prop makes the Calendar's value immutable. Unlike isDisabled
, the Calendar remains focusable.
<MyCalendar
aria-label="Event date"
value={today(getLocalTimeZone())}
isReadOnly
/>
<MyCalendar
aria-label="Event date"
value={today(getLocalTimeZone())}
isReadOnly
/>
<MyCalendar
aria-label="Event date"
value={today(
getLocalTimeZone()
)}
isReadOnly
/>
Error message#
Calendar
tries to avoid allowing the user to select invalid dates in the first place (see Validation and Unavailable dates above). However, if according to application logic a selected date is invalid, the validationState
prop can be set to "invalid"
. This alerts assistive technology users that the selection is invalid, and can be used for styling purposes as well. In addition, the errorMessage
slot may be used to help the user fix the issue.
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 (
<MyCalendar
aria-label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid ? 'invalid' : 'valid'}
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 (
<MyCalendar
aria-label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid ? 'invalid' : 'valid'}
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 (
<MyCalendar
aria-label="Appointment date"
value={date}
onChange={setDate}
validationState={isInvalid
? 'invalid'
: 'valid'}
errorMessage={isInvalid
? 'We are closed on weekends'
: null}
/>
);
}
Labeling#
An aria-label must be provided to the Calendar
for accessibility. If it is labeled by a separate element, an aria-labelledby
prop must be provided using the id
of the labeling element instead.
Internationalization#
In order to internationalize a Calendar
, a localized string should be passed to the aria-label
prop. For languages that are read right-to-left (e.g. Hebrew and Arabic), keyboard navigation is automatically flipped. Ensure that your CSS accounts for this as well. Dates are automatically formatted using the current locale.
Advanced customization#
Composition#
If you need to customize one of the components within a Calendar
, such as CalendarGrid
or CalendarCell
, in many cases you can create a wrapper component. This lets you customize the props passed to the component.
function MyCalendarCell(props) {
return <CalendarCell {...props} className="my-item" />
}
function MyCalendarCell(props) {
return <CalendarCell {...props} className="my-item" />
}
function MyCalendarCell(
props
) {
return (
<CalendarCell
{...props}
className="my-item"
/>
);
}
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 useCalendar for more details.