alpha

Calendar

Calendars display a grid of days in one or more months and allow users to select a single date.

installyarn add @react-spectrum/calendar
version3.0.0-alpha.4
usageimport {Calendar} from '@react-spectrum/calendar'

Example#


<Calendar aria-label="Event date" />
<Calendar aria-label="Event date" />
<Calendar aria-label="Event date" />

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 (
    <Flex gap="size-300" wrap>
      <Calendar
        aria-label="Date (uncontrolled)"
        defaultValue={parseDate('2020-02-03')} />
      <Calendar
        aria-label="Date (controlled)"
        value={value}
        onChange={setValue} />
    </Flex>
  );
}
import {parseDate} from '@internationalized/date';

function Example() {
  let [value, setValue] = React.useState(
    parseDate('2020-02-03')
  );

  return (
    <Flex gap="size-300" wrap>
      <Calendar
        aria-label="Date (uncontrolled)"
        defaultValue={parseDate('2020-02-03')}
      />
      <Calendar
        aria-label="Date (controlled)"
        value={value}
        onChange={setValue}
      />
    </Flex>
  );
}
import {parseDate} from '@internationalized/date';

function Example() {
  let [value, setValue] =
    React.useState(
      parseDate(
        '2020-02-03'
      )
    );

  return (
    <Flex
      gap="size-300"
      wrap
    >
      <Calendar
        aria-label="Date (uncontrolled)"
        defaultValue={parseDate(
          '2020-02-03'
        )}
      />
      <Calendar
        aria-label="Date (controlled)"
        value={value}
        onChange={setValue}
      />
    </Flex>
  );
}

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 Provider 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 {Provider} from '@adobe/react-spectrum';

function Example() {
  let [date, setDate] = React.useState(null);
  return (
    <Provider locale="hi-IN-u-ca-indian">
      <Calendar aria-label="Date" value={date} onChange={setDate} />
      <p>Selected date: {date?.toString()}</p>
    </Provider>
  );
}
import {Provider} from '@adobe/react-spectrum';

function Example() {
  let [date, setDate] = React.useState(null);
  return (
    <Provider locale="hi-IN-u-ca-indian">
      <Calendar
        aria-label="Date"
        value={date}
        onChange={setDate}
      />
      <p>Selected date: {date?.toString()}</p>
    </Provider>
  );
}
import {Provider} from '@adobe/react-spectrum';

function Example() {
  let [date, setDate] =
    React.useState(null);
  return (
    <Provider locale="hi-IN-u-ca-indian">
      <Calendar
        aria-label="Date"
        value={date}
        onChange={setDate}
      />
      <p>
        Selected date:
        {' '}
        {date
          ?.toString()}
      </p>
    </Provider>
  );
}

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), the layout of the Calendar is automatically flipped. Dates are automatically formatted using the current locale.

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 {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@adobe/react-spectrum';

function Example() {
  let [date, setDate] = React.useState(parseDate('2022-07-04'));
  let formatter = useDateFormatter({dateStyle: 'full'});

  return (
    <>
      <Calendar aria-label="Event date" value={date} onChange={setDate} />
      <p>Selected date: {formatter.format(date.toDate(getLocalTimeZone()))}</p>
    </>
  );
}
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@adobe/react-spectrum';

function Example() {
  let [date, setDate] = React.useState(
    parseDate('2022-07-04')
  );
  let formatter = useDateFormatter({ dateStyle: 'full' });

  return (
    <>
      <Calendar
        aria-label="Event date"
        value={date}
        onChange={setDate}
      />
      <p>
        Selected date:{' '}
        {formatter.format(date.toDate(getLocalTimeZone()))}
      </p>
    </>
  );
}
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@adobe/react-spectrum';

function Example() {
  let [date, setDate] =
    React.useState(
      parseDate(
        '2022-07-04'
      )
    );
  let formatter =
    useDateFormatter({
      dateStyle: 'full'
    });

  return (
    <>
      <Calendar
        aria-label="Event date"
        value={date}
        onChange={setDate}
      />
      <p>
        Selected date:
        {' '}
        {formatter
          .format(
            date.toDate(
              getLocalTimeZone()
            )
          )}
      </p>
    </>
  );
}

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';

<Calendar
  aria-label="Appointment date"
  minValue={today(getLocalTimeZone())}
/>
import {today} from '@internationalized/date';

<Calendar
  aria-label="Appointment date"
  minValue={today(getLocalTimeZone())}
/>
import {today} from '@internationalized/date';

<Calendar
  aria-label="Appointment date"
  minValue={today(
    getLocalTimeZone()
  )}
/>

Unavailable dates#

Calendar supports marking certain dates as unavailable. These dates cannot be selected by the user and are displayed with a crossed out appearance. 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 {isWeekend, today} from '@internationalized/date';
import {useLocale} from '@adobe/react-spectrum';

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 (
    <Calendar
      aria-label="Appointment date"
      minValue={today(getLocalTimeZone())}
      isDateUnavailable={isDateUnavailable}
    />
  );
}
import {isWeekend, today} from '@internationalized/date';
import {useLocale} from '@adobe/react-spectrum';

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 (
    <Calendar
      aria-label="Appointment date"
      minValue={today(getLocalTimeZone())}
      isDateUnavailable={isDateUnavailable}
    />
  );
}
import {
  isWeekend,
  today
} from '@internationalized/date';
import {useLocale} from '@adobe/react-spectrum';

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 (
    <Calendar
      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 (
    <Flex direction="column" alignItems="start" gap="size-200">
      <ActionButton onPress={() => setFocusedDate(defaultDate)}>
        Reset focused date
      </ActionButton>
      <Calendar focusedValue={focusedDate} onFocusChange={setFocusedDate} />
    </Flex>
  );
}
import {CalendarDate} from '@internationalized/date';

function Example() {
  let defaultDate = new CalendarDate(2021, 7, 1);
  let [focusedDate, setFocusedDate] = React.useState(
    defaultDate
  );

  return (
    <Flex
      direction="column"
      alignItems="start"
      gap="size-200"
    >
      <ActionButton
        onPress={() => setFocusedDate(defaultDate)}
      >
        Reset focused date
      </ActionButton>
      <Calendar
        focusedValue={focusedDate}
        onFocusChange={setFocusedDate}
      />
    </Flex>
  );
}
import {CalendarDate} from '@internationalized/date';

function Example() {
  let defaultDate =
    new CalendarDate(
      2021,
      7,
      1
    );
  let [
    focusedDate,
    setFocusedDate
  ] = React.useState(
    defaultDate
  );

  return (
    <Flex
      direction="column"
      alignItems="start"
      gap="size-200"
    >
      <ActionButton
        onPress={() =>
          setFocusedDate(
            defaultDate
          )}
      >
        Reset focused
        date
      </ActionButton>
      <Calendar
        focusedValue={focusedDate}
        onFocusChange={setFocusedDate}
      />
    </Flex>
  );
}

Props#


NameTypeDefaultDescription
visibleMonthsnumber1The number of months to display at once. Up to 3 months are supported.
minValueDateValueThe minimum allowed date that a user may select.
maxValueDateValueThe maximum allowed date that a user may select.
isDateUnavailable( (date: DateValue )) => booleanCallback that is called for each date of the calendar. If it returns true, then the date is unavailable.
isDisabledbooleanfalseWhether the calendar is disabled.
isReadOnlybooleanfalseWhether the calendar value is immutable.
autoFocusbooleanfalseWhether to automatically focus the calendar when it mounts.
focusedValueDateValueControls the currently focused date within the calendar.
defaultFocusedValueDateValueThe date that is focused when the calendar first mounts (uncountrolled).
valueTThe current value (controlled).
defaultValueTThe default value (uncontrolled).
Events
NameTypeDefaultDescription
onFocusChange( (date: CalendarDate )) => voidHandler that is called when the focused date changes.
onChange( (value: <T> )) => voidHandler that is called when the value changes.
Layout
NameTypeDefaultDescription
flexResponsive<stringnumberboolean>When used in a flex layout, specifies how the element will grow or shrink to fit the space available. See MDN.
flexGrowResponsive<number>When used in a flex layout, specifies how the element will grow to fit the space available. See MDN.
flexShrinkResponsive<number>When used in a flex layout, specifies how the element will shrink to fit the space available. See MDN.
flexBasisResponsive<numberstring>When used in a flex layout, specifies the initial main size of the element. See MDN.
alignSelfResponsive<'auto''normal''start''end''center''flex-start''flex-end''self-start''self-end''stretch'>Overrides the alignItems property of a flex or grid container. See MDN.
justifySelfResponsive<'auto''normal''start''end''flex-start''flex-end''self-start''self-end''center''left''right''stretch'>Specifies how the element is justified inside a flex or grid container. See MDN.
orderResponsive<number>The layout order for the element within a flex or grid container. See MDN.
gridAreaResponsive<string>When used in a grid layout, specifies the named grid area that the element should be placed in within the grid. See MDN.
gridColumnResponsive<string>When used in a grid layout, specifies the column the element should be placed in within the grid. See MDN.
gridRowResponsive<string>When used in a grid layout, specifies the row the element should be placed in within the grid. See MDN.
gridColumnStartResponsive<string>When used in a grid layout, specifies the starting column to span within the grid. See MDN.
gridColumnEndResponsive<string>When used in a grid layout, specifies the ending column to span within the grid. See MDN.
gridRowStartResponsive<string>When used in a grid layout, specifies the starting row to span within the grid. See MDN.
gridRowEndResponsive<string>When used in a grid layout, specifies the ending row to span within the grid. See MDN.
Spacing
NameTypeDefaultDescription
marginResponsive<DimensionValue>The margin for all four sides of the element. See MDN.
marginTopResponsive<DimensionValue>The margin for the top side of the element. See MDN.
marginBottomResponsive<DimensionValue>The margin for the bottom side of the element. See MDN.
marginStartResponsive<DimensionValue>The margin for the logical start side of the element, depending on layout direction. See MDN.
marginEndResponsive<DimensionValue>The margin for the logical end side of an element, depending on layout direction. See MDN.
marginXResponsive<DimensionValue>The margin for both the left and right sides of the element. See MDN.
marginYResponsive<DimensionValue>The margin for both the top and bottom sides of the element. See MDN.
Sizing
NameTypeDefaultDescription
widthResponsive<DimensionValue>The width of the element. See MDN.
minWidthResponsive<DimensionValue>The minimum width of the element. See MDN.
maxWidthResponsive<DimensionValue>The maximum width of the element. See MDN.
heightResponsive<DimensionValue>The height of the element. See MDN.
minHeightResponsive<DimensionValue>The minimum height of the element. See MDN.
maxHeightResponsive<DimensionValue>The maximum height of the element. See MDN.
Positioning
NameTypeDefaultDescription
positionResponsive<'static''relative''absolute''fixed''sticky'>Specifies how the element is positioned. See MDN.
topResponsive<DimensionValue>The top position for the element. See MDN.
bottomResponsive<DimensionValue>The bottom position for the element. See MDN.
leftResponsive<DimensionValue>The left position for the element. See MDN. Consider using start instead for RTL support.
rightResponsive<DimensionValue>The right position for the element. See MDN. Consider using start instead for RTL support.
startResponsive<DimensionValue>The logical start position for the element, depending on layout direction. See MDN.
endResponsive<DimensionValue>The logical end position for the element, depending on layout direction. See MDN.
zIndexResponsive<number>The stacking order for the element. See MDN.
isHiddenResponsive<boolean>Hides the element.
Accessibility
NameTypeDefaultDescription
idstringThe element's unique identifier. See MDN.
Advanced
NameTypeDefaultDescription
UNSAFE_classNamestringSets the CSS className for the element. Only use as a last resort. Use style props instead.
UNSAFE_styleCSSPropertiesSets inline style for the element. Only use as a last resort. Use style props instead.

Visual options#


Disabled#

<Calendar aria-label="Event date" isDisabled />
<Calendar aria-label="Event date" isDisabled />
<Calendar
  aria-label="Event date"
  isDisabled
/>

Read only#

The isReadOnly boolean prop makes the Calendar's value immutable. Unlike isDisabled, the Calendar remains focusable.

<Calendar
  aria-label="Event date"
  value={today(getLocalTimeZone())}
  isReadOnly
/>
<Calendar
  aria-label="Event date"
  value={today(getLocalTimeZone())}
  isReadOnly
/>
<Calendar
  aria-label="Event date"
  value={today(
    getLocalTimeZone()
  )}
  isReadOnly
/>

Visible months#

By default, the Calendar displays a single month. The visibleMonths prop allows displaying up to 3 months at a time.

<div style={{maxWidth: '100%', overflow: 'auto'}}>
  <Calendar aria-label="Event date" visibleMonths={3} />
</div>
<div style={{maxWidth: '100%', overflow: 'auto'}}>
  <Calendar aria-label="Event date" visibleMonths={3} />
</div>
<div
  style={{
    maxWidth: '100%',
    overflow: 'auto'
  }}
>
  <Calendar
    aria-label="Event date"
    visibleMonths={3}
  />
</div>