# Calendar

A month grid for picking a date, several dates or a range.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"

export default function CalendarDemo() {
  const [date, setDate] = useState<Date | undefined>(new Date(2025, 5, 12))
  return <Calendar mode="single" defaultMonth={date} selected={date} onSelect={setDate} />
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/calendar
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Button](https://www.arene.style/docs/components/button) and [Select](https://www.arene.style/docs/components/select).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install react-day-picker @stylexjs/stylex clsx @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` from the same page.
   Calendar also needs the [Button](https://www.arene.style/docs/components/button) for the month
   arrows, the [Select](https://www.arene.style/docs/components/select) for the style its month and year
   dropdowns share, and `interop.css`, which sizes the arrow icons.

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/calendar.tsx"
   "use client"

   import { useEffect, useRef, type ComponentProps } from "react"
   import {
     DayPicker,
     defaultDateLib,
     getDefaultClassNames,
     type ChevronProps,
     type ClassNames,
     type DateRange,
     type DayButtonProps,
     type DayPickerProps,
     type DayProps,
     type DropdownProps,
   } from "react-day-picker"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import { CaretDownIcon } from "@phosphor-icons/react/dist/csr/CaretDown"
   import { CaretLeftIcon } from "@phosphor-icons/react/dist/csr/CaretLeft"
   import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
   import { CaretUpIcon } from "@phosphor-icons/react/dist/csr/CaretUp"

   import { Button } from "@/components/ui/button"
   import { selectStyles } from "@/components/ui/select"
   import { breakpoints } from "@/theme/breakpoints.stylex"
   import { states } from "@/theme/states"
   import { color, duration, ease, layer, leading, radius, space, text } from "@/theme/tokens.stylex"

   const cellSize = "var(--arene-calendar-cell-size)"

   const styles = stylex.create({
     root: {
       position: "relative",
       width: "fit-content",
       padding: space.s3,
       fontSize: text.sm,
       lineHeight: leading.sm,
       "--arene-calendar-cell-size": space.s8,
     },
     day: {
       width: cellSize,
       height: cellSize,
       padding: 0,
       textAlign: "center",
     },
     rangeStart: {
       backgroundColor: color.muted,
       borderStartStartRadius: radius.lg,
       borderEndStartRadius: radius.lg,
     },
     rangeMiddle: {
       backgroundColor: color.muted,
       borderStartStartRadius: { default: 0, ":first-of-type": radius.lg },
       borderEndStartRadius: { default: 0, ":first-of-type": radius.lg },
       borderStartEndRadius: { default: 0, ":last-of-type": radius.lg },
       borderEndEndRadius: { default: 0, ":last-of-type": radius.lg },
     },
     rangeEnd: {
       backgroundColor: color.muted,
       borderStartEndRadius: radius.lg,
       borderEndEndRadius: radius.lg,
     },
     dayButton: {
       position: "relative",
       zIndex: { default: null, ":focus-visible": layer.raised },
       display: "flex",
       alignItems: "center",
       justifyContent: "center",
       width: cellSize,
       height: cellSize,
       padding: 0,
       borderRadius: radius.lg,
       borderWidth: 1,
       borderStyle: "solid",
       backgroundColor: { default: color.transparent, ":hover": color.itemHighlightBg },
       color: color.foreground,
       fontSize: text.sm,
       lineHeight: leading.sm,
       fontVariantNumeric: "tabular-nums",
       userSelect: "none",
       transitionProperty: "color, background-color, border-color, box-shadow",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
     },
     outside: { color: color.mutedForeground },
     today: { backgroundColor: color.muted, fontWeight: 500 },
     rangeMiddleButton: {
       "--arene-border-color": color.transparent,
       borderRadius: 0,
       backgroundColor: { default: color.transparent, ":hover": color.itemHighlightBg },
       color: color.foreground,
     },
     navButton: { pointerEvents: "auto" },
     dropdownRoot: { position: "relative", display: "inline-flex" },
     dropdown: {
       appearance: "none",
       paddingInlineEnd: space.s6,
       fontWeight: 500,
     },
     dropdownIcon: {
       position: "absolute",
       insetBlock: 0,
       insetInlineEnd: space.s2,
       width: space.s3_5,
       height: "100%",
       color: color.mutedForeground,
       pointerEvents: "none",
     },
   })

   const parts = stylex.create({
     months: {
       position: "relative",
       display: "flex",
       flexDirection: { default: "column", [breakpoints.md]: "row" },
       gap: space.s4,
     },
     month: { display: "flex", flexDirection: "column", gap: space.s3 },
     nav: {
       position: "absolute",
       insetBlockStart: 0,
       insetInline: 0,
       display: "flex",
       alignItems: "center",
       justifyContent: "space-between",
       height: cellSize,
       pointerEvents: "none",
     },
     month_caption: {
       display: "flex",
       alignItems: "center",
       justifyContent: "center",
       height: cellSize,
       paddingInline: cellSize,
     },
     caption_label: { fontWeight: 500, whiteSpace: "nowrap", userSelect: "none" },
     dropdowns: { display: "flex", alignItems: "center", gap: space.s1_5 },
     month_grid: { borderCollapse: "collapse" },
     weekday: {
       width: cellSize,
       paddingBlockEnd: space.s1,
       fontSize: text.xs,
       lineHeight: leading.xs,
       fontWeight: 400,
       color: color.mutedForeground,
       userSelect: "none",
     },
     week_number_header: { width: cellSize },
     week_number: {
       width: cellSize,
       fontSize: text.xs,
       lineHeight: leading.xs,
       fontWeight: 400,
       color: color.mutedForeground,
       fontVariantNumeric: "tabular-nums",
       userSelect: "none",
     },
     footer: { paddingBlockStart: space.s3, color: color.mutedForeground },
   })

   type CalendarPart = keyof typeof parts

   const calendarStyles = {
     root: styles.root,
     parts,
     day: styles.day,
     dayButton: [styles.dayButton, states.focusRing],
     outside: styles.outside,
     today: styles.today,
     selected: states.choiceChecked,
     disabled: states.disabled,
     range: { start: styles.rangeStart, middle: styles.rangeMiddle, end: styles.rangeEnd },
   }

   const defaultClassNames = getDefaultClassNames()

   function partClassNames(classNames: Partial<ClassNames> = {}): Partial<ClassNames> {
     const merged: Partial<ClassNames> = { ...classNames }
     for (const part of Object.keys(parts) as CalendarPart[]) {
       merged[part] = clsx(
         defaultClassNames[part],
         stylex.props(parts[part]).className,
         classNames[part],
       )
     }
     return merged
   }

   function focusableDay(container: HTMLElement | null) {
     return (
       container?.querySelector<HTMLElement>("[data-slot='calendar'] td button[tabindex='0']") ?? null
     )
   }

   function CalendarDay({ day: _day, modifiers, className, style, ...props }: DayProps) {
     const sx = stylex.props(
       styles.day,
       modifiers.range_start && styles.rangeStart,
       modifiers.range_middle && styles.rangeMiddle,
       modifiers.range_end && styles.rangeEnd,
     )
     return (
       <td
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   function CalendarDayButton({ day: _day, modifiers, className, style, ...props }: DayButtonProps) {
     const ref = useRef<HTMLButtonElement>(null)

     useEffect(() => {
       if (modifiers.focused) ref.current?.focus()
     }, [modifiers.focused])

     const sx = stylex.props(
       styles.dayButton,
       states.focusRing,
       modifiers.outside && styles.outside,
       modifiers.today && styles.today,
       modifiers.selected && states.choiceChecked,
       modifiers.range_middle && styles.rangeMiddleButton,
       modifiers.disabled && states.disabled,
     )

     return (
       <button
         ref={ref}
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
       />
     )
   }

   function CalendarNavButton(props: ComponentProps<"button">) {
     return (
       <Button
         variant="ghost"
         size="icon-sm"
         xstyle={[styles.navButton, props["aria-disabled"] && states.disabled]}
         {...props}
       />
     )
   }

   const chevrons = {
     up: CaretUpIcon,
     down: CaretDownIcon,
     left: CaretLeftIcon,
     right: CaretRightIcon,
   }

   function CalendarChevron({ orientation = "left", className, style }: ChevronProps) {
     const Icon = chevrons[orientation]
     return <Icon aria-hidden="true" className={className} style={style} />
   }

   function CalendarDropdown({ options, className, style, ...props }: DropdownProps) {
     const sx = stylex.props(
       selectStyles.trigger,
       selectStyles.sizes.sm,
       styles.dropdown,
       props.disabled && selectStyles.triggerDisabled,
     )
     return (
       <span {...stylex.props(styles.dropdownRoot)}>
         <select
           {...sx}
           {...props}
           className={clsx(sx.className, className)}
           style={{ ...sx.style, ...style }}
         >
           {options?.map(({ value, label, disabled }) => (
             <option key={value} value={value} disabled={disabled}>
               {label}
             </option>
           ))}
         </select>
         <CaretDownIcon aria-hidden="true" {...stylex.props(styles.dropdownIcon)} />
       </span>
     )
   }

   type CalendarProps = DayPickerProps & {
     animate?: never
     xstyle?: StyleXStyles
   }

   function Calendar({
     showOutsideDays = true,
     classNames,
     components,
     formatters,
     xstyle,
     className,
     style,
     ...props
   }: CalendarProps) {
     const sx = stylex.props(styles.root, xstyle)
     return (
       <DayPicker
         data-slot="calendar"
         showOutsideDays={showOutsideDays}
         {...props}
         className={clsx(sx.className, className)}
         style={{ ...sx.style, ...style }}
         classNames={partClassNames(classNames)}
         formatters={{
           formatMonthDropdown: (month, dateLib = defaultDateLib) => dateLib.format(month, "LLL"),
           ...formatters,
         }}
         components={{
           Day: CalendarDay,
           DayButton: CalendarDayButton,
           PreviousMonthButton: CalendarNavButton,
           NextMonthButton: CalendarNavButton,
           Chevron: CalendarChevron,
           Dropdown: CalendarDropdown,
           ...components,
         }}
       />
     )
   }

   export {
     Calendar,
     CalendarDayButton,
     calendarStyles,
     focusableDay,
     type CalendarProps,
     type DateRange,
   }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { Calendar } from "@/components/ui/calendar"
```

```tsx
const [date, setDate] = useState<Date | undefined>(new Date())

return <Calendar mode="single" selected={date} onSelect={setDate} />
```

Calendar is [React DayPicker](https://daypicker.dev) with arene's styles on
every part. Selection, keyboard navigation, locales and disabled-date matchers
all come from DayPicker, and every DayPicker prop works.

## Range

`mode="range"` selects a start and an end. The days between them sit on a
continuous band, and `numberOfMonths` lays months side by side from the `md`
breakpoint, stacked below it.

```tsx
"use client"

import { useState } from "react"
import { Calendar, type DateRange } from "@/components/ui/calendar"

export default function CalendarRange() {
  const [range, setRange] = useState<DateRange | undefined>({
    from: new Date(2025, 5, 12),
    to: new Date(2025, 6, 4),
  })
  return (
    <Calendar
      mode="range"
      numberOfMonths={2}
      defaultMonth={range?.from}
      selected={range}
      onSelect={setRange}
    />
  )
}
```

## Multiple

`mode="multiple"` toggles each day it is given.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"

export default function CalendarMultiple() {
  const [dates, setDates] = useState<Date[] | undefined>([
    new Date(2025, 5, 3),
    new Date(2025, 5, 12),
    new Date(2025, 5, 13),
    new Date(2025, 5, 24),
  ])
  return (
    <Calendar
      mode="multiple"
      defaultMonth={new Date(2025, 5)}
      selected={dates}
      onSelect={setDates}
    />
  )
}
```

## Month and year dropdowns

`captionLayout="dropdown"` swaps the caption for a month and a year dropdown.
`startMonth` and `endMonth` bound the years they list. They are native `select`
elements, so a phone opens its own wheel picker.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"

export default function CalendarDropdown() {
  const [date, setDate] = useState<Date | undefined>(new Date(2025, 5, 12))
  return (
    <Calendar
      mode="single"
      captionLayout="dropdown"
      startMonth={new Date(1950, 0)}
      endMonth={new Date(2030, 11)}
      defaultMonth={date}
      selected={date}
      onSelect={setDate}
    />
  )
}
```

## Disabled days

`disabled` takes a date, an array of dates or a matcher. This one rules out
weekends and every day before the 9th.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"

export default function CalendarDisabled() {
  const [date, setDate] = useState<Date | undefined>(new Date(2025, 5, 12))
  return (
    <Calendar
      mode="single"
      defaultMonth={date}
      selected={date}
      onSelect={setDate}
      disabled={[{ before: new Date(2025, 5, 9) }, { dayOfWeek: [0, 6] }]}
    />
  )
}
```

## Week numbers

`showWeekNumber` adds a column of ISO week numbers. `weekStartsOn={1}` starts
the week on Monday to match them.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"

export default function CalendarWeekNumbers() {
  const [date, setDate] = useState<Date | undefined>(new Date(2025, 5, 12))
  return (
    <Calendar
      mode="single"
      showWeekNumber
      weekStartsOn={1}
      defaultMonth={date}
      selected={date}
      onSelect={setDate}
    />
  )
}
```

> **Note**
>
> A calendar rendered on the server shows the server's month and today. Pass
> `defaultMonth` when the HTML is prerendered, or the page shows the month it
> was built in until the visitor changes it. A calendar inside a popover renders
> only in the browser, so it does not have this problem.

## API reference

Calendar accepts every [DayPicker prop](https://daypicker.dev/api/type-aliases/DayPickerProps)
except `animate`. It changes one default and adds `xstyle`.

| Prop              | Type                        | Default |
| ----------------- | --------------------------- | ------- |
| `showOutsideDays` | `boolean`                   | `true`  |
| `xstyle`          | `StyleXStyles`              | —       |
| `className`       | `string`                    | —       |
| `style`           | `CSSProperties`             | —       |
| `classNames`      | `Partial<ClassNames>`       | —       |
| `components`      | `Partial<CustomComponents>` | —       |

`classNames` adds to arene's classes instead of replacing them, so a plain CSS
hook can sit on any part. Every part keeps DayPicker's own `rdp-*` class too.
`components` replaces a part outright. `CalendarDayButton` is exported so a
custom `DayButton` can wrap it rather than rebuild the day states.

The month dropdown shows short month names. Pass `formatters` with your own
`formatMonthDropdown` to change it.

### Cell size

Every day, weekday and caption is `--arene-calendar-cell-size` square, `2rem`
by default. Set it through `xstyle` to resize the grid.

### calendarStyles

The style maps behind the component: `root`, `parts` (keyed by DayPicker's part
names), `day`, `dayButton`, `outside`, `today`, `selected`, `disabled` and
`range`.

### Data attributes

| Attribute                                      | On         | Effect                           |
| ---------------------------------------------- | ---------- | -------------------------------- |
| `data-slot="calendar"`                         | the root   | Calendar root                    |
| `data-selected`, `data-today`, `data-outside`  | a day cell | DayPicker writes the day's state |
| `data-disabled`, `data-hidden`, `data-focused` | a day cell | DayPicker writes the day's state |
