# Date Picker

A field that opens a calendar in a popover.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"
import { DatePicker, DatePickerContent, DatePickerTrigger } from "@/components/ui/date-picker"

const format = new Intl.DateTimeFormat("en-US", { dateStyle: "long" })

export default function DatePickerDemo() {
  const [open, setOpen] = useState(false)
  const [date, setDate] = useState<Date>()
  return (
    <DatePicker open={open} onOpenChange={setOpen}>
      <DatePickerTrigger aria-label="Date">{date && format.format(date)}</DatePickerTrigger>
      <DatePickerContent>
        <Calendar
          mode="single"
          selected={date}
          onSelect={(next) => {
            setDate(next)
            setOpen(false)
          }}
        />
      </DatePickerContent>
    </DatePicker>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/date-picker
```

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

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex @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 `state-styles.ts` and
   `field-state.ts` from the same page. The date picker also needs the
   [Calendar](https://www.arene.style/docs/components/calendar), the [Popover](https://www.arene.style/docs/components/popover)
   it opens in, and the [Select](https://www.arene.style/docs/components/select), whose trigger style it
   shares.

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

   ```tsx title="components/ui/date-picker.tsx"
   "use client"

   import { use, useRef, type CSSProperties, type ReactNode } from "react"
   import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { CalendarBlankIcon } from "@phosphor-icons/react/dist/csr/CalendarBlank"

   import { focusableDay } from "@/components/ui/calendar"
   import { PopoverContent } from "@/components/ui/popover"
   import { selectStyles } from "@/components/ui/select"
   import { FieldStateContext } from "@/lib/field-state"
   import { stateStyles } from "@/lib/state-styles"
   import { color, space, width } from "@/theme/tokens.stylex"

   const styles = stylex.create({
     trigger: { minWidth: width.narrow, justifyContent: "flex-start", gap: space.s2 },
     icon: { display: "flex", color: color.mutedForeground },
     value: {
       display: "block",
       flexGrow: 1,
       minWidth: 0,
       overflow: "hidden",
       textOverflow: "ellipsis",
       textAlign: "start",
     },
     content: { width: "auto", padding: 0, gap: 0 },
   })

   type Overrides = { xstyle?: StyleXStyles; className?: string }

   type StateOverrides = Overrides & { style?: CSSProperties }

   function DatePicker<Payload>(props: PopoverPrimitive.Root.Props<Payload>) {
     return <PopoverPrimitive.Root {...props} />
   }

   type DatePickerTriggerProps<Payload> = Omit<
     PopoverPrimitive.Trigger.Props<Payload>,
     "className" | "style"
   > &
     StateOverrides & {
       size?: keyof typeof selectStyles.sizes
       placeholder?: ReactNode
       icon?: ReactNode
     }

   function DatePickerTrigger<Payload>({
     xstyle,
     style,
     className,
     size = "default",
     placeholder = "Pick a date",
     icon = <CalendarBlankIcon aria-hidden="true" />,
     "aria-invalid": ariaInvalid,
     children,
     ...props
   }: DatePickerTriggerProps<Payload>) {
     const fieldState = use(FieldStateContext)
     const invalid = ariaInvalid != null && ariaInvalid !== false
     const empty = children == null || children === false || children === ""
     return (
       <PopoverPrimitive.Trigger
         data-slot="date-picker-trigger"
         data-size={size}
         data-placeholder={empty || undefined}
         aria-invalid={invalid || undefined}
         {...props}
         {...stateStyles(
           (state: PopoverPrimitive.Trigger.State) => [
             selectStyles.trigger,
             selectStyles.sizes[size],
             styles.trigger,
             empty && selectStyles.triggerPlaceholder,
             (fieldState?.valid === false || invalid) && selectStyles.invalid,
             state.disabled && selectStyles.triggerDisabled,
             xstyle,
           ],
           { className, style, hook: "arene-icons" },
         )}
       >
         <span {...stylex.props(styles.icon)}>{icon}</span>
         <span {...stylex.props(styles.value)}>{empty ? placeholder : children}</span>
       </PopoverPrimitive.Trigger>
     )
   }

   type DatePickerContentProps = Parameters<typeof PopoverContent>[0]

   function DatePickerContent({ ref, xstyle, initialFocus, ...props }: DatePickerContentProps) {
     const popup = useRef<HTMLDivElement | null>(null)

     const setRef = (node: HTMLDivElement | null) => {
       popup.current = node
       if (typeof ref === "function") ref(node)
       else if (ref) ref.current = node
     }

     return (
       <PopoverContent
         ref={setRef}
         data-slot="date-picker-content"
         align="start"
         initialFocus={initialFocus ?? (() => focusableDay(popup.current) ?? true)}
         xstyle={[styles.content, xstyle]}
         {...props}
       />
     )
   }

   export { DatePicker, DatePickerContent, DatePickerTrigger }
   ```

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

## Usage

```tsx
import { Calendar } from "@/components/ui/calendar"
import { DatePicker, DatePickerContent, DatePickerTrigger } from "@/components/ui/date-picker"
```

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

return (
  <DatePicker>
    <DatePickerTrigger>{date?.toLocaleDateString()}</DatePickerTrigger>
    <DatePickerContent>
      <Calendar mode="single" selected={date} onSelect={setDate} />
    </DatePickerContent>
  </DatePicker>
)
```

## Composition

```text
DatePicker                  popover root
├── DatePickerTrigger       the field; shows children, or placeholder when empty
└── DatePickerContent       popup, sized to what it holds
    └── Calendar
```

The trigger shows whatever you pass as children, so you choose the date format.
With no children it shows `placeholder`. The popup has no padding of its own;
the calendar brings its own.

To close the popup once a date is picked, control `open` and set it to `false`
in `onSelect`, as the first example does.

Opening the popup moves focus to the selected day, or to today when nothing is
selected, so the arrow keys move through dates straight away.

## Range

Pass a range calendar. `Intl.DateTimeFormat.formatRange` writes both ends
without repeating the month or year they share.

```tsx
"use client"

import { useState } from "react"
import { Calendar, type DateRange } from "@/components/ui/calendar"
import { DatePicker, DatePickerContent, DatePickerTrigger } from "@/components/ui/date-picker"

const format = new Intl.DateTimeFormat("en-US", { dateStyle: "medium" })

export default function DatePickerRange() {
  const [range, setRange] = useState<DateRange>()
  return (
    <DatePicker>
      <DatePickerTrigger aria-label="Dates" placeholder="Pick a range">
        {range?.from && range.to && format.formatRange(range.from, range.to)}
      </DatePickerTrigger>
      <DatePickerContent>
        <Calendar
          mode="range"
          numberOfMonths={2}
          defaultMonth={range?.from}
          selected={range}
          onSelect={setRange}
        />
      </DatePickerContent>
    </DatePicker>
  )
}
```

## Date of birth

Month and year dropdowns get to a date decades back without paging through
every month. `endMonth` stops the years at today.

```tsx
"use client"

import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"
import { DatePicker, DatePickerContent, DatePickerTrigger } from "@/components/ui/date-picker"

const format = new Intl.DateTimeFormat("en-US", { dateStyle: "long" })

export default function DatePickerDropdown() {
  const [open, setOpen] = useState(false)
  const [date, setDate] = useState<Date>()
  return (
    <DatePicker open={open} onOpenChange={setOpen}>
      <DatePickerTrigger aria-label="Date of birth" placeholder="Date of birth">
        {date && format.format(date)}
      </DatePickerTrigger>
      <DatePickerContent>
        <Calendar
          mode="single"
          captionLayout="dropdown"
          startMonth={new Date(1920, 0)}
          endMonth={new Date()}
          defaultMonth={date ?? new Date(1995, 0)}
          selected={date}
          onSelect={(next) => {
            setDate(next)
            setOpen(false)
          }}
        />
      </DatePickerContent>
    </DatePicker>
  )
}
```

## API reference

`DatePicker` is the Base UI `Popover` root and takes its props. See the
[Base UI reference](https://base-ui.com/react/components/popover).

### DatePickerTrigger

Wraps `Popover.Trigger` and accepts its props, plus:

| Prop           | Type                | Default         |
| -------------- | ------------------- | --------------- |
| `placeholder`  | `ReactNode`         | `"Pick a date"` |
| `icon`         | `ReactNode`         | calendar icon   |
| `size`         | `"default" \| "sm"` | `"default"`     |
| `aria-invalid` | `boolean`           | —               |
| `xstyle`       | `StyleXStyles`      | —               |
| `className`    | `string`            | —               |
| `style`        | `CSSProperties`     | —               |

Inside a `Field`, the trigger shows the invalid ring when the field is invalid.

### DatePickerContent

Takes every `PopoverContent` prop. `align` defaults to `"start"`, and
`initialFocus` defaults to the calendar's focusable day.

### Data attributes

| Attribute                         | On          | Effect                         |
| --------------------------------- | ----------- | ------------------------------ |
| `data-slot="date-picker-trigger"` | the trigger | Trigger                        |
| `data-placeholder`                | the trigger | Present while nothing is shown |
| `data-size`                       | the trigger | Trigger size                   |
| `data-slot="date-picker-content"` | the popup   | Popup surface                  |
