{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:react-aria-components';
import i18nDocs from 'docs:@internationalized/date';
import ariaDocs from 'docs:@react-aria/calendar';
import statelyDocs from 'docs:@react-stately/calendar';
import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} from '@react-spectrum/docs';
import styles from '@react-spectrum/docs/src/docs.css';
import packageData from 'react-aria-components/package.json';
import Anatomy from '/packages/react-aria/docs/calendar/calendar-anatomy.svg';
import ChevronRight from '@spectrum-icons/workflow/ChevronRight';
import {Divider} from '@react-spectrum/divider';
import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard';
import Button from '@react-spectrum/docs/pages/assets/component-illustrations/ActionButton.svg';
import InternationalizedDate from '@react-spectrum/docs/pages/assets/component-illustrations/InternationalizedDate.svg';
import {StarterKits} from '@react-spectrum/docs/src/StarterKits';

---
category: Date and Time
keywords: [input, form, field, date, time]
type: component
---

# Calendar

<PageDescription>{docs.exports.Calendar.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['Calendar']} />

## Example

```tsx example
import {Calendar, Heading, Button, CalendarGrid, CalendarCell} from 'react-aria-components';
import {ChevronLeft, ChevronRight} from 'lucide-react';

<Calendar aria-label="Appointment date">
  <header>
    <Button slot="previous"><ChevronLeft size={20} /></Button>
    <Heading />
    <Button slot="next"><ChevronRight size={20} /></Button>
  </header>
  <CalendarGrid>
    {date => <CalendarCell date={date} />}
  </CalendarGrid>
</Calendar>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
```css hidden
@import './Button.mdx' layer(button);
```

```css
@import "@react-aria/example-theme";

.react-aria-Calendar {
  width: fit-content;
  max-width: 100%;
  color: var(--text-color);

  header {
    display: flex;
    align-items: center;
    margin: 0 4px .5rem 4px;

    .react-aria-Heading {
      flex: 1;
      margin: 0;
      text-align: center;
      font-size: 1.375rem;
    }
  }

  .react-aria-Button {
    width: 2rem;
    height: 2rem;
    padding: 0;
  }

  .react-aria-CalendarCell {
    width: 2rem;
    line-height: 2rem;
    text-align: center;
    border-radius: 6px;
    cursor: default;
    outline: none;
    margin: 1px;
    forced-color-adjust: none;

    &[data-outside-month] {
      display: none;
    }

    &[data-pressed] {
      background: var(--gray-100);
    }

    &[data-focus-visible] {
      outline: 2px solid var(--focus-ring-color);
      outline-offset: 2px;
    }

    &[data-selected] {
      background: var(--highlight-background);
      color: var(--highlight-foreground);
    }
  }
}
```

</details>

## 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](../blog/date-and-time-pickers-for-all.html) for more details about the internationalization, accessibility, and user experience features implemented by `Calendar`.

## Anatomy

<Anatomy
  role="img"
  aria-label="Anatomy diagram of a calendar component, which consists of a heading, grid of cells, previous, and next buttons." />

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.

```tsx
import {Calendar, Heading, Button, CalendarGrid, CalendarGridHeader, CalendarHeaderCell, CalendarGridBody, CalendarCell, Text} from 'react-aria-components';

<Calendar>
  <Button slot="previous" />
  <Heading />
  <Button slot="next" />
  <CalendarGrid>
    <CalendarGridHeader>
      {day => <CalendarHeaderCell />}
    </CalendarGridHeader>
    <CalendarGridBody>
      {date => <CalendarCell date={date} />}
    </CalendarGridBody>
  </CalendarGrid>
  <Text slot="errorMessage" />
</Calendar>
```

Note that much of this anatomy is shared with [range calendars](RangeCalendar.html). If you have both, the styling and internal components such as `CalendarCell` can be shared.

### Concepts

`Calendar` makes use of the following concepts:

<section className={styles.cardGroup} data-size="small">

<ExampleCard
  url="../internationalized/date/index.html"
  title="@internationalized/date"
  description="Represent and manipulate dates and times in a locale-aware manner.">
  <InternationalizedDate />
</ExampleCard>

</section>

### Composed components

A `Calendar` uses the following components, which may also be used standalone or reused in other components.

<section className={styles.cardGroup} data-size="small">

<ExampleCard
  url="Button.html"
  title="Button"
  description="A button allows a user to perform an action.">
  <Button />
</ExampleCard>

</section>

## Starter kits

To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured [Storybook](https://storybook.js.org/) that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="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](#error-message)).

```tsx example export=true
import type {CalendarProps, DateValue} from 'react-aria-components';
import {Text} from 'react-aria-components';

interface MyCalendarProps<T extends DateValue> extends CalendarProps<T> {
  errorMessage?: string
}

function MyCalendar<T extends DateValue>({errorMessage, ...props}: MyCalendarProps<T>) {
  return (
    <Calendar {...props}>
      <header>
        <Button slot="previous"><ChevronLeft size={20} /></Button>
        <Heading />
        <Button slot="next"><ChevronRight size={20} /></Button>
      </header>
      <CalendarGrid>
        {date => <CalendarCell date={date} />}
      </CalendarGrid>
      {errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
    </Calendar>
  );
}

<MyCalendar 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](../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 <TypeLink links={i18nDocs.links} type={i18nDocs.exports.CalendarDate} /> objects in the `onChange` event, but if a <TypeLink links={i18nDocs.links} type={i18nDocs.exports.CalendarDateTime} /> or <TypeLink links={i18nDocs.links} type={i18nDocs.exports.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.

```tsx example
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>
  );
}
```

### 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#adding_a_calendar_in_the_locale_string), passed to the [I18nProvider](I18nProvider.html) 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.

```tsx example
import {I18nProvider} from '@react-aria/i18n';

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

### Custom calendar systems

`Calendar` also supports custom calendar systems that implement custom business rules. An example would be a fiscal year calendar that follows a [4-5-4 format](https://nrf.com/resources/4-5-4-calendar), where month ranges don't follow the usual Gregorian calendar.

The `createCalendar` prop accepts a function that returns an instance of the <TypeLink links={i18nDocs.links} type={i18nDocs.exports.Calendar} /> interface. See the [@internationalized/date docs](../internationalized/date/Calendar.html#custom-calendars) for an example implementation.

```tsx import
import type {AnyCalendarDate} from '@internationalized/date';
import {CalendarDate, startOfWeek, toCalendar} from '@internationalized/date';
```

```tsx example
import {GregorianCalendar} from '@internationalized/date';

function Example() {
  return <MyCalendar firstDayOfWeek="sun" createCalendar={() => new Custom454()} />;
}

class Custom454 extends GregorianCalendar {
  // See @internationalized/date docs linked above...
  ///- begin collapse -///
  weekPattern = [4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4];
  getDaysInMonth(date) {
    return this.weekPattern[date.month - 1] * 7;
  }

  fromJulianDay(jd: number): CalendarDate {
    let gregorian = super.fromJulianDay(jd);

    let monthStart = startOfWeek(new CalendarDate(gregorian.year, 1, 1), 'en');
    for (let months = 0; months < this.weekPattern.length; months++) {
      let weeksInMonth = this.weekPattern[months];
      let monthEnd = monthStart.add({weeks: weeksInMonth});
      if (monthEnd.compare(gregorian) > 0) {
        let days = gregorian.compare(monthStart);
        return new CalendarDate(this, monthStart.year, months + 1, days + 1);
      }
      monthStart = monthEnd;
    }

    throw Error('Date is not in any month somehow!');
  }

  toJulianDay(date: AnyCalendarDate): number {
    let monthStart = startOfWeek(new CalendarDate(date.year, 1, 1), 'en');
    for (let month = 1; month < date.month; month++) {
      monthStart = monthStart.add({weeks: this.weekPattern[month - 1]});
    }

    let gregorian = monthStart.add({days: date.day - 1});
    return super.toJulianDay(gregorian);
  }

  getFormattableMonth(date) {
    let gregorian = toCalendar(date, new GregorianCalendar());
    return gregorian.set({month: date.month, day: 1});
  }

  isEqual(other) {
    return other instanceof Custom454;
  }
 ///- end collapse -///
}
```

## 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.

```tsx example
import {getLocalTimeZone} from '@internationalized/date';
import {useDateFormatter} from '@react-aria/i18n';

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>
    </>
  );
}
```

## 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.

```tsx example
<Calendar aria-label="Appointment date" visibleDuration={{months: 3}}>
  <header>
    <Button slot="previous"><ChevronLeft size={20} /></Button>
    <Heading />
    <Button slot="next"><ChevronRight size={20} /></Button>
  </header>
  <div style={{display: 'flex', gap: 30, overflow: 'auto'}}>
    <CalendarGrid>
      {date => <CalendarCell date={date} />}
    </CalendarGrid>
    <CalendarGrid offset={{months: 1}}>
      {date => <CalendarCell date={date} />}
    </CalendarGrid>
    <CalendarGrid offset={{months: 2}}>
      {date => <CalendarCell date={date} />}
    </CalendarGrid>
  </div>
</Calendar>
```

### Page behavior

The `pageBehavior` prop allows you to control how the calendar navigates between months. By default, the calendar will navigate by `visibleDuration`, but by setting `pageBehavior` to `single`, pagination will be by one month.

```tsx example
<Calendar aria-label="Appointment date" visibleDuration={{months: 3}} pageBehavior="single">
  <header>
    <Button slot="previous"><ChevronLeft size={20} /></Button>
    <Heading />
    <Button slot="next"><ChevronRight size={20} /></Button>
  </header>
  <div style={{display: 'flex', gap: 30, overflow: 'auto'}}>
    <CalendarGrid>
      {date => <CalendarCell date={date} />}
    </CalendarGrid>
    <CalendarGrid offset={{months: 1}}>
      {date => <CalendarCell date={date} />}
    </CalendarGrid>
    <CalendarGrid offset={{months: 2}}>
      {date => <CalendarCell date={date} />}
    </CalendarGrid>
  </div>
</Calendar>
```

## 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.

```tsx example
import {today} from '@internationalized/date';

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

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-Calendar {
  .react-aria-CalendarCell {
    &[data-disabled] {
      color: var(--text-color-disabled);
    }
  }
}
```

</details>

### 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.


```tsx example
import {today, isWeekend} from '@internationalized/date';
import {useLocale} from '@react-aria/i18n';

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: DateValue) => 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} />
}
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-Calendar {
  .react-aria-CalendarCell {
    &[data-unavailable] {
      text-decoration: line-through;
      color: var(--invalid-color);
    }
  }
}
```

</details>

### Error message

`Calendar` tries to avoid allowing the user to select invalid dates in the first place (see [Validation](#validation) and [Unavailable dates](#unavailable-dates) above). However, if according to application logic a selected date is invalid, the `isInvalid` prop can be set. 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.

```tsx example
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}
      /*- begin highlight -*/
      isInvalid={isInvalid}
      errorMessage={isInvalid ? 'We are closed on weekends' : undefined}
      /*- end highlight -*/
    />
  );
}
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-Calendar {
  .react-aria-CalendarCell {
    &[data-invalid] {
      background: var(--invalid-color);
      color: var(--highlight-foreground);
    }
  }

  [slot=errorMessage] {
    font-size: 12px;
    color: var(--invalid-color);
  }
}
```

</details>

## 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.

```tsx example
import {CalendarDate} from '@internationalized/date';

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

  return (
    <>
      <button style={{marginBottom: 20}} onClick={() => setFocusedDate(defaultDate)}>Reset focused date</button>
      <MyCalendar focusedValue={focusedDate} onFocusChange={setFocusedDate} />
    </>
  );
}
```

## Disabled

The `isDisabled` boolean prop makes the Calendar disabled. Cells cannot be focused or selected.

```tsx example
<MyCalendar aria-label="Event date" isDisabled />
```

### Read only

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

```tsx example
<MyCalendar aria-label="Event date" value={today(getLocalTimeZone())} isReadOnly />
```

## Custom first day of week

By default, the first day of the week is automatically set based on the current locale. This can be changed by setting the `firstDayOfWeek` prop to `'sun'`, `'mon'`, `'tue'`, `'wed'`, `'thu'`, `'fri'`, or `'sat'`.

```tsx example
<MyCalendar aria-label="Event date" value={today(getLocalTimeZone())} firstDayOfWeek="mon" />
```

## 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.

## Props

### Calendar

<PropTable component={docs.exports.Calendar} links={docs.links} />

### 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`.

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary>

<PropTable component={docs.exports.Button} links={docs.links} />

</details>

### 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. This renders a default `<CalendarGridHeader>`, which displays the weekday names in the column headers. This can be customized by providing a `<CalendarGridHeader>` and `<CalendarGridBody>` as children instead of a function.

<PropTable component={docs.exports.CalendarGrid} links={docs.links} />

### CalendarGridHeader

A `<CalendarGridHeader>` renders the header within a `<CalendarGrid>`, displaying a list of weekday names. It accepts a function as its `children`, which is called with a day name abbreviation to render a `<CalendarHeaderCell>` for each column header.

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary>

<PropTable component={docs.exports.CalendarGridHeader} links={docs.links} />

</details>

### CalendarHeaderCell

A `<CalendarHeaderCell>` renders a column header within a `<CalendarGridHeader>`. It typically displays a weekday name.

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary>

<PropTable component={docs.exports.CalendarHeaderCell} links={docs.links} />

</details>

### CalendarGridBody

A `<CalendarGridBody>` renders the body within a `<CalendarGrid>`. It accepts a function as its `children`, which is called to render a `<CalendarCell>` for each date.

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary>

<PropTable component={docs.exports.CalendarGridBody} links={docs.links} />

</details>

### CalendarCell

A `<CalendarCell>` renders an individual date within a `<CalendarGrid>`.

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary>

<PropTable component={docs.exports.CalendarCell} links={docs.links} />

</details>

## 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.

```css
.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.

```jsx
<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 data attributes, which you can target in CSS selectors. For example:

```css
.react-aria-CalendarCell[data-selected] {
  /* ... */
}

.react-aria-CalendarCell[data-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](https://tailwindcss.com/).

```jsx
<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.

```jsx
<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 supports the following states and render props:

<StateTable properties={docs.exports.CalendarRenderProps.properties} />

### Button

A [Button](Button.html) 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:

<StateTable properties={docs.exports.ButtonRenderProps.properties} />

### CalendarGrid

A `CalendarGrid` can be targeted with the `.react-aria-CalendarGrid` CSS selector, or by overriding with a custom `className`. When a function is provided as children, a default `<CalendarGridHeader>` and `<CalendarGridBody>` are rendered. If you need to customize the styling of the header cells, you can render them yourself.

```tsx example
import {CalendarGridHeader, CalendarHeaderCell, CalendarGridBody} from 'react-aria-components';

<Calendar aria-label="Appointment date">
  <header>
    <Button slot="previous"><ChevronLeft size={20} /></Button>
    <Heading />
    <Button slot="next"><ChevronRight size={20} /></Button>
  </header>
  <CalendarGrid>
    <CalendarGridHeader>
      {day => <CalendarHeaderCell style={{color: 'var(--blue)'}}>{day}</CalendarHeaderCell>}
    </CalendarGridHeader>
    <CalendarGridBody>
      {date => <CalendarCell date={date} />}
    </CalendarGridBody>
  </CalendarGrid>
</Calendar>
````

### CalendarGridHeader

A `CalendarGridHeader` can be targeted with the `.react-aria-CalendarGridHeader` CSS selector, or by overriding with a custom `className`.

### CalendarHeaderCell

A `CalendarHeaderCell` can be targeted with the `.react-aria-CalendarHeaderCell` CSS selector, or by overriding with a custom `className`.

### CalendarGridBody

A `CalendarGridBody` can be targeted with the `.react-aria-CalendarGridBody` 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:

<StateTable properties={docs.exports.CalendarCellRenderProps.properties} />

### Text

The error message element within a `Calendar` can be targeted with the `[slot=errorMessage]` CSS selector, or by adding a custom `className`.

## 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.

```tsx
function MyCalendarCell(props) {
  return <CalendarCell {...props} className="my-item" />
}
```

### Contexts

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in [mergeProps](mergeProps.html)).

<ContextTable components={['Calendar']} docs={docs} />

This example uses `CalendarContext` to create a composite component containing a calendar and buttons representing preset dates. The <TypeLink links={docs.links} type={docs.exports.useSlottedContext} /> hook can be used to consume contexts that support the `slot` prop.

```tsx example render=false export=true
import {CalendarContext, useSlottedContext} from 'react-aria-components';

function CalendarPicker({children}) {
  let [value, onChange] = React.useState(null);
  let [focusedValue, onFocusChange] = React.useState(null);

  return (
    /*- begin highlight -*/
    <CalendarContext.Provider value={{value, onChange, focusedValue, onFocusChange}}>
    {/*- end highlight -*/}
      <div className="calendar-picker">
        {children}
      </div>
    </CalendarContext.Provider>
  );
}

interface PresetProps {
  date: CalendarDate,
  children: React.ReactNode
}

function Preset({date, children}: PresetProps) {
  /*- begin highlight -*/
  let context = useSlottedContext(CalendarContext)!;
  /*- end highlight -*/
  let onPress = () => {
    context.onFocusChange(date);
    context.onChange(date);
  };

  return (
    <Button onPress={onPress}>{children}</Button>
  );
}
```

Now you can combine a `Calendar` and one or more `Preset` components in a `CalendarPicker`.

```tsx example
import {startOfWeek, startOfMonth} from '@internationalized/date';
import {useLocale} from 'react-aria';

function Example() {
  let {locale} = useLocale();
  let now = today(getLocalTimeZone());

  return (
    <CalendarPicker>
      <Preset date={now}>Today</Preset>
      <Preset date={startOfWeek(now.add({weeks: 1}), locale)}>Next week</Preset>
      <Preset date={startOfMonth(now.add({months: 1}))}>Next month</Preset>
      <MyCalendar aria-label="Meeting date" />
    </CalendarPicker>
  );
}
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.calendar-picker {
  > .react-aria-Button {
    margin: 0 4px 8px 4px;
  }
}
```

</details>

### Custom children

Calendar passes props to its child components, such as the heading and buttons, via their associated contexts. These contexts are exported so you can also consume them in your own custom components. This enables you to reuse existing components from your app or component library together with React Aria Components.

<ContextTable components={['Heading', 'Button', 'Text']} docs={docs} />

This example consumes from `HeadingContext` in an existing styled heading component to make it compatible with React Aria Components. The <TypeLink links={docs.links} type={docs.exports.useContextProps} /> hook merges the local props and ref with the ones provided via context by Calendar.

```tsx
import type {HeadingProps} from 'react-aria-components';
import {HeadingContext, useContextProps} from 'react-aria-components';

const MyCustomHeading = React.forwardRef((props: HeadingProps, ref: React.ForwardedRef<HTMLHeadingElement>) => {
  // Merge the local props and ref with the ones provided via context.
  ///- begin highlight -///
  [props, ref] = useContextProps(props, ref, HeadingContext);
  ///- end highlight -///

  // ... your existing Heading component
  return <h2 {...props} ref={ref} />;
});
```

Now you can use `MyCustomHeading` within a `Calendar`, in place of the builtin React Aria Components `Heading`.

```tsx
<Calendar>
  {/*- begin highlight -*/}
  <MyCustomHeading />
  {/*- end highlight -*/}
  {/* ... */}
</Calendar>
```

### State

Calendar provides a <TypeLink links={statelyDocs.links} type={statelyDocs.exports.CalendarState} /> object to its children via `CalendarStateContext`. This can be used to access and manipulate the calendar's state.

This example shows a `CalendarValue` component that can be placed within a `Calendar` to display the currently selected date as a formatted string.

```tsx example
import {CalendarStateContext} from 'react-aria-components';
import {useDateFormatter} from 'react-aria';

function CalendarValue() {
  /*- begin highlight -*/
  let state = React.useContext(CalendarStateContext)!;
  /*- end highlight -*/
  let date = state.value?.toDate(getLocalTimeZone());
  let formatter = useDateFormatter();
  let formatted = date ? formatter.format(date) : 'None';
  return <small>Selected date: {formatted}</small>;
}

<Calendar>
  <header>
    <Button slot="previous"><ChevronLeft size={20} /></Button>
    <Heading />
    <Button slot="next"><ChevronRight size={20} /></Button>
  </header>
  <CalendarGrid>
    {date => <CalendarCell date={date} />}
  </CalendarGrid>
  {/*- begin highlight -*/}
  <CalendarValue />
  {/*- end highlight -*/}
</Calendar>
```

### 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](useCalendar.html) for more details.

This example uses the <TypeLink links={ariaDocs.links} type={ariaDocs.exports.useCalendarGrid} /> hook to build a single week calendar view.

```tsx example render=false export=true
import type {CalendarGridProps} from 'react-aria-components';
import {CalendarStateContext} from 'react-aria-components';
import {useCalendarGrid} from 'react-aria';

function WeekCalendarGrid(props: CalendarGridProps) {
  let state = React.useContext(CalendarStateContext)!;
  let {gridProps} = useCalendarGrid(props, state);

  return (
    <table {...gridProps}>
      <tbody>
        <tr>
          {state.getDatesInWeek(0).map((date, i) => <CalendarCell key={i} date={date} />)}
        </tr>
      </tbody>
    </table>
  );
}
```

`WeekCalendarGrid` can be used within a `Calendar` in place of the default `CalendarGrid` component.

```tsx example
<Calendar visibleDuration={{weeks: 1}} defaultValue={today(getLocalTimeZone())}>
  <div className="week">
    <Heading />
    <Button slot="previous"><ChevronLeft size={20} /></Button>
    <WeekCalendarGrid />
    <Button slot="next"><ChevronRight size={20} /></Button>
  </div>
</Calendar>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.week {
  display: grid;
  grid-template-areas:
    "heading heading heading"
    "previous grid next";
  align-items: center;
  justify-items: center;
  gap: 8px;

  .react-aria-Heading {
    grid-area: heading;
    margin: 0;
    font-size: 1.2rem;
  }

  .react-aria-CalendarCell[data-outside-month] {
    display: block;
  }
}
```

</details>
