# DateRangePicker

## Introduction

DateRangePicker is a form input component that allows users to select a date range (start date and end date) from a calendar popup or by typing directly into the input field. It supports flexible date formatting, date restrictions, and both controlled and uncontrolled modes.

DateRangePicker is ideal for booking systems, reporting filters, scheduling, and any scenario requiring a start-to-end date selection. For single date selection, use DatePicker instead. For month-level granularity, use MonthRangePicker.

```tsx
<DateRangePicker onChange={onChange} />
```

| Field           | Description | Default |
| --------------- | ----------- | ------- |
| name            | —           | —       |
| value           | —           | —       |
| defaultValue    | —           | —       |
| disabled        | —           | —       |
| required        | —           | —       |
| label           | —           | —       |
| error           | —           | —       |
| helperText      | —           | —       |
| minDate         | —           | —       |
| maxDate         | —           | —       |
| disableFuture   | —           | —       |
| disablePast     | —           | —       |
| format          | —           | —       |
| displayFormat   | —           | —       |
| inputReadOnly   | —           | —       |
| hideClearButton | —           | —       |
| size            | —           | —       |
| numberOfMonths  | —           | —       |

> **Use built-in form props**
>
> This component natively supports form elements such as `label` and `helperText` props.
> When building forms, use these built-in props instead of manually composing labels and helper text with Typography.
>
> ```tsx
> // Recommended: use built-in props
> <DateRangePicker label="Period" helperText="Select start and end dates" />
>
> // Not recommended: manually composing with Typography
> <FormControl>
>   <Typography level="title-sm" component="label">Period</Typography>
>   <DateRangePicker />
>   <Typography level="body-xs" color="neutral">Select start and end dates</Typography>
> </FormControl>
> ```

## Usage

```tsx
import { DateRangePicker } from '@ceed/cds';

function DateRangeForm() {
  const [dateRange, setDateRange] = useState('');

  return <DateRangePicker label="Select Date Range" value={dateRange} onChange={(e) => setDateRange(e.target.value)} />;
}
```

## Sizes

DateRangePicker supports three sizes (`sm`, `md`, `lg`) to fit different layouts and density requirements.

```tsx
<Stack gap={2}>
    <DateRangePicker size="sm" />
    <DateRangePicker size="md" />
    <DateRangePicker size="lg" />
  </Stack>
```

## Form Features

### Label

Add a label above the date range picker using the `label` prop.

```tsx
<DateRangePicker
  onChange={onChange}
  label="Date Range"
/>
```

### Helper Text

Provide additional guidance below the input using the `helperText` prop.

```tsx
<DateRangePicker
  onChange={onChange}
  label="Date"
  helperText="Please select a date"
/>
```

### Error State

Display validation errors by combining the `error` and `helperText` props.

```tsx
<DateRangePicker
  onChange={onChange}
  label="Date"
  helperText="Please select a date"
  error
/>
```

### Required Field

Mark the field as required in forms. This displays a required indicator next to the label.

```tsx
<DateRangePicker
  onChange={onChange}
  label="Label"
  helperText="I'm helper text"
  required
/>
```

## Date Restrictions

### Minimum Date

Restrict selection to dates on or after a specified minimum date using the `minDate` prop.

```tsx
<DateRangePicker
  onChange={onChange}
  minDate="2024-04-10"
/>
```

### Maximum Date

Restrict selection to dates on or before a specified maximum date using the `maxDate` prop.

```tsx
<DateRangePicker
  onChange={onChange}
  maxDate="2024-04-10"
/>
```

### Disable Future Dates

Prevent selection of dates in the future using `disableFuture`. Useful for report filters and historical data queries.

```tsx
<DateRangePicker
  onChange={onChange}
  disableFuture
/>
```

### Disable Past Dates

Prevent selection of dates in the past using `disablePast`. Useful for booking and scheduling forms.

```tsx
<DateRangePicker
  onChange={onChange}
  disablePast
/>
```

## Controlled vs Uncontrolled

### Controlled

In controlled mode, the parent component manages the date range state via `value` and `onChange`. This gives full control over the value, allowing programmatic updates.

```tsx
<Stack gap={2}>
    <DateRangePicker
      {...args}
      onChange={(e) => {
        args.onChange?.(e);
        setValue(e.target.value);
      }}
      value={value}
    />
    <Button
      onClick={() => {
        const [start, end] = value.split(" - ");
        function shiftMonth(dateString: string) {
          const currentValue = new Date(dateString);
          currentValue.setMonth(currentValue.getMonth() + 1);
          const year = currentValue.getFullYear();
          const month = String(currentValue.getMonth() + 1).padStart(2, "0");
          const day = String(currentValue.getDate()).padStart(2, "0");
          return `${year}/${month}/${day}`;
        }
        setValue(`${shiftMonth(start)} - ${shiftMonth(end)}`);
      }}
    >
      Shift Month
    </Button>
  </Stack>
```

### Uncontrolled

In uncontrolled mode, the component manages its own state internally. Set an initial value with `defaultValue` and use `onChange` to react to user selections.

```tsx
<DateRangePicker
  onChange={onChange}
  label="Uncontrolled DateRangePicker"
  helperText="Please select a date"
  defaultValue="2024/04/01 - 2025/04/01"
/>
```

## Formatting

### Value Format (`format`)

The `format` prop controls the format of the value returned in `onChange`. The input always displays in `YYYY/MM/DD` by default, but the `onChange` value follows the specified format.

```tsx
<Stack gap={2}>
    <DateRangePicker
      {...args}
      value={value1}
      label="YYYY.MM.DD"
      name="YYYY.MM.DD"
      format="YYYY.MM.DD"
      onChange={(e) => {
        setValue1(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value2}
      label="YYYY/MM/DD"
      name="YYYY/MM/DD"
      format="YYYY/MM/DD"
      onChange={(e) => {
        setValue2(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value3}
      label="MM/DD/YYYY"
      name="MM/DD/YYYY"
      format="MM/DD/YYYY"
      onChange={(e) => {
        setValue3(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value4}
      label="YYYY-MM-DD"
      name="YYYY-MM-DD"
      format="YYYY-MM-DD"
      onChange={(e) => {
        setValue4(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value5}
      label="DD/MM/YYYY"
      name="DD/MM/YYYY"
      format="DD/MM/YYYY"
      onChange={(e) => {
        setValue5(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value6}
      label="DD.MM.YYYY"
      name="DD.MM.YYYY"
      format="DD.MM.YYYY"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
  </Stack>
```

### Display Format (`displayFormat`)

The `displayFormat` prop controls what the user sees in the input field. This is independent of the `format` prop, allowing you to store data in one format while displaying another.

```tsx
<Stack gap={2}>
    <DateRangePicker
      {...args}
      value={value1}
      label="YYYY.MM.DD"
      name="YYYY.MM.DD"
      displayFormat="YYYY.MM.DD"
      onChange={(e) => {
        setValue1(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value2}
      label="YYYY/MM/DD"
      name="YYYY/MM/DD"
      displayFormat="YYYY/MM/DD"
      onChange={(e) => {
        setValue2(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value3}
      label="MM/DD/YYYY"
      name="MM/DD/YYYY"
      displayFormat="MM/DD/YYYY"
      onChange={(e) => {
        setValue3(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value4}
      label="YYYY-MM-DD"
      name="YYYY-MM-DD"
      displayFormat="YYYY-MM-DD"
      onChange={(e) => {
        setValue4(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value5}
      label="DD/MM/YYYY"
      name="DD/MM/YYYY"
      displayFormat="DD/MM/YYYY"
      onChange={(e) => {
        setValue5(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DateRangePicker
      {...args}
      value={value6}
      label="DD.MM.YYYY"
      name="DD.MM.YYYY"
      displayFormat="DD.MM.YYYY"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
  </Stack>
```

**Supported format tokens:**

| Token  | Description   | Example |
| ------ | ------------- | ------- |
| `YYYY` | 4-digit year  | 2024    |
| `MM`   | 2-digit month | 04      |
| `DD`   | 2-digit day   | 15      |

```tsx
// format affects onChange value; displayFormat affects what users see
<DateRangePicker
  format="YYYY-MM-DD" // onChange returns "2024-04-01 - 2024-04-15"
  displayFormat="MM/DD/YYYY" // Input shows "04/01/2024 - 04/15/2024"
/>
```

## Interaction Modes

### Disabled

Prevent all user interaction when the component is disabled.

```tsx
<DateRangePicker
  onChange={onChange}
  disabled
/>
```

### Input Read Only

Allow calendar selection only while preventing direct typing. Useful on mobile devices where keyboard input is impractical.

```tsx
<DateRangePicker
  onChange={onChange}
  defaultValue="2024/05/03 - 2024/06/03"
  inputReadOnly
/>
```

### Read Only

Fully read-only state where neither typing nor calendar selection is available. Use this to display a date range value without allowing changes.

```tsx
<DateRangePicker
  onChange={onChange}
  value="2024/05/03 - 2024/06/03"
  readOnly
/>
```

## Dual Calendar

Use the `numberOfMonths` prop to display two calendar months side by side in the popup. This gives users a wider view of the date range without navigating back and forth, and is especially useful for selecting ranges that span across months.

```tsx
<DateRangePicker
  onChange={onChange}
  numberOfMonths={2}
  label="Date Range"
/>
```

When combined with `presets`, the dual calendar provides a fast, at-a-glance interface for report and analytics date filters.

```tsx
<DateRangePicker
    {...args}
    value={value}
    onChange={(e) => {
      setValue(e.target.value);
      args.onChange?.(e);
    }}
    disableFuture
    presets={[
      {
        label: "Today",
        value: `${fmt(today)} - ${fmt(today)}`
      },
      {
        label: "Last 7 days",
        value: range(7)
      },
      {
        label: "Last 1 month",
        value: range(1, "months")
      },
      {
        label: "Last 3 months",
        value: range(3, "months")
      },
      {
        label: "Last 6 months",
        value: range(6, "months")
      }
    ]}
  />
```

```tsx
<DateRangePicker numberOfMonths={2} label="Date Range" />
```

**Navigation behavior with two calendars:**

- The left calendar shows only the **previous** (◀) button.
- The right calendar shows only the **next** (▶) button.
- Each click advances the view by **1 month**, keeping the two calendars consecutive.
- Range selection and hover preview work across both calendars seamlessly.

## Additional Options

### Presets

Use the `presets` prop to display quick-select options alongside the calendar, such as "Last 7 days" or "Last 1 month". The preset panel appears to the right of the calendar inside the popup, providing one-click access to commonly used date ranges.

Each preset's `value` must match the component's `format` prop and use the `-` separator (e.g., `"2026/03/01 - 2026/04/03"`). When the current value matches a preset, that preset is automatically highlighted -- regardless of whether the value was set via the preset button or by selecting the same range on the calendar.

```tsx
<DateRangePicker
    {...args}
    value={value}
    onChange={(e) => {
      setValue(e.target.value);
      args.onChange?.(e);
    }}
    presets={[
      {
        label: "Today",
        value: `${fmt(today)} - ${fmt(today)}`
      },
      {
        label: "Last 3 days",
        value: range(3)
      },
      {
        label: "Last 7 days",
        value: range(7)
      },
      {
        label: "Last 1 month",
        value: range(1, "months")
      },
      {
        label: "Last 3 months",
        value: range(3, "months")
      },
      {
        label: "Last 6 months",
        value: range(6, "months")
      }
    ]}
  />
```

```tsx
import { DateRangePicker } from '@ceed/cds';

function ReportFilter() {
  const [dateRange, setDateRange] = useState('');
  const today = new Date();
  const fmt = (d: Date) =>
    `${d.getFullYear()}/${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}`;
  const monthsAgo = (n: number) => {
    const d = new Date(today);
    d.setMonth(d.getMonth() - n);
    return `${fmt(d)} - ${fmt(today)}`;
  };

  return (
    <DateRangePicker
      label="Report Period"
      value={dateRange}
      onChange={(e) => setDateRange(e.target.value)}
      disableFuture
      presets={[
        { label: 'Last 7 days', value: `${fmt(new Date(today.getTime() - 7 * 86400000))} - ${fmt(today)}` },
        { label: 'Last 1 month', value: monthsAgo(1) },
        { label: 'Last 3 months', value: monthsAgo(3) },
        { label: 'Last 6 months', value: monthsAgo(6) },
      ]}
    />
  );
}
```

### Hide Clear Button

Remove the clear button from the calendar popup using `hideClearButton`.

```tsx
<DateRangePicker
  onChange={onChange}
  defaultValue="2024/05/03 - 2024/06/03"
  hideClearButton
/>
```

### With Reset Button

Example of integrating an external reset button to clear the selected date range programmatically.

```tsx
<div
    style={{
      display: "flex",
      gap: "10px"
    }}
  >
    <DateRangePicker
      {...props}
      value={value}
      onChange={(event) => {
        setValue(event.target.value);
      }}
    />
    <Button onClick={() => setValue("")}>Reset</Button>
  </div>
```

## Booking Form

```tsx
function BookingForm() {
  const [dates, setDates] = useState('');
  const [error, setError] = useState('');

  const handleChange = (e) => {
    const value = e.target.value;
    setDates(value);

    if (!value) {
      setError('Please select dates');
    } else {
      const [start, end] = value.split(' - ');
      const days = (new Date(end) - new Date(start)) / (1000 * 60 * 60 * 24);
      setError(days > 30 ? 'Maximum stay is 30 days' : '');
    }
  };

  return (
    <DateRangePicker
      label="Check-in / Check-out"
      value={dates}
      onChange={handleChange}
      error={!!error}
      helperText={error || 'Select your stay dates'}
      disablePast
      required
    />
  );
}
```

## Report Date Filter

```tsx
function ReportFilters({ onFilter }) {
  const [dateRange, setDateRange] = useState('');

  const handleApply = () => {
    if (!dateRange) return;
    const [startDate, endDate] = dateRange.split(' - ');
    onFilter({ startDate, endDate });
  };

  return (
    <Stack direction="row" gap={2} alignItems="flex-end">
      <DateRangePicker
        label="Report Period"
        value={dateRange}
        onChange={(e) => setDateRange(e.target.value)}
        format="YYYY-MM-DD"
        disableFuture
        helperText="Select date range for the report"
      />
      <Button onClick={handleApply}>Apply Filter</Button>
    </Stack>
  );
}
```

## Separate API and Display Formats

```tsx
function DataExport() {
  const [dateRange, setDateRange] = useState('');

  return (
    <DateRangePicker
      label="Export Period"
      value={dateRange}
      onChange={(e) => setDateRange(e.target.value)}
      format="YYYY-MM-DD"
      displayFormat="DD/MM/YYYY"
      disableFuture
      required
    />
  );
}
```

## Best Practices

1. **Match `value` to `format`**: The `value` and `defaultValue` strings must always match the `format` prop. Mismatched formats will cause unexpected behavior.

```tsx
// Correct: value matches format
<DateRangePicker format="YYYY-MM-DD" value="2024-04-01 - 2024-04-15" />

// Incorrect: value does not match format
<DateRangePicker format="YYYY/MM/DD" value="04/01/2024 - 04/15/2024" />
```

2. **Use `displayFormat` to separate concerns**: Store data in an API-friendly format (e.g., `YYYY-MM-DD`) while displaying a user-friendly format (e.g., `MM/DD/YYYY`).

```tsx
// Store ISO format, display locale format
<DateRangePicker format="YYYY-MM-DD" displayFormat="MM/DD/YYYY" />
```

3. **Use `inputReadOnly` on mobile**: On touch devices, keyboard input for date ranges is error-prone. Use `inputReadOnly` to force calendar selection.

```tsx
// Better mobile experience
<DateRangePicker inputReadOnly />
```

4. **Set reasonable date boundaries**: Use `minDate`, `maxDate`, `disablePast`, or `disableFuture` to prevent users from selecting invalid ranges.

```tsx
// Restrict to a specific period
<DateRangePicker minDate="2024-01-01" maxDate="2024-12-31" />
```

5. **Display contextual helper text**: Show the duration or additional context in the `helperText` to help users understand their selection.

```tsx
const getDuration = (value) => {
  if (!value) return 'Select dates';
  const [start, end] = value.split(' - ').map((d) => new Date(d));
  const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24));
  return `${days} day${days !== 1 ? 's' : ''} selected`;
};

<DateRangePicker helperText={getDuration(dateRange)} />;
```

## Props and Customization

### Key Props

| Prop              | Type                                                    | Default        | Description                                                                                                          |
| ----------------- | ------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------- |
| `value`           | `string \| null`                                        | -              | Selected date range string in `format` (controlled mode)                                                             |
| `defaultValue`    | `string`                                                | -              | Initial date range string (uncontrolled mode)                                                                        |
| `onChange`        | `(event: { target: { name?, value: string } }) => void` | -              | Callback when the date range changes                                                                                 |
| `format`          | `string`                                                | `'YYYY/MM/DD'` | Format of the `value` and `onChange` value                                                                           |
| `displayFormat`   | `string`                                                | `'YYYY/MM/DD'` | Format displayed in the input field. Supports `MMM` (short month name) and `MMMM` (full month name) tokens           |
| `locale`          | `string`                                                | `'default'`    | Locale for month names when using `MMM`/`MMMM` tokens in `displayFormat` (BCP 47 format, e.g., `'en-US'`, `'ko-KR'`) |
| `label`           | `ReactNode`                                             | -              | Form label displayed above the input                                                                                 |
| `helperText`      | `ReactNode`                                             | -              | Helper text displayed below the input                                                                                |
| `error`           | `boolean`                                               | `false`        | Applies danger color to indicate validation error                                                                    |
| `required`        | `boolean`                                               | `false`        | Marks the field as required                                                                                          |
| `disabled`        | `boolean`                                               | `false`        | Disables the entire component                                                                                        |
| `name`            | `string`                                                | -              | HTML name attribute for form submission                                                                              |
| `minDate`         | `string`                                                | -              | Minimum selectable date (in `format`)                                                                                |
| `maxDate`         | `string`                                                | -              | Maximum selectable date (in `format`)                                                                                |
| `disableFuture`   | `boolean`                                               | `false`        | Disables all future dates                                                                                            |
| `disablePast`     | `boolean`                                               | `false`        | Disables all past dates                                                                                              |
| `inputReadOnly`   | `boolean`                                               | `false`        | Prevents keyboard typing; calendar-only input that opens on clicking either the input or the calendar button         |
| `hideClearButton` | `boolean`                                               | `false`        | Hides the clear button in the calendar popup                                                                         |
| `numberOfMonths`  | `number`                                                | `1`            | Number of calendar months to show side by side in the popup                                                          |

> **Note**: For a **controlled** field that starts empty, pass `null` as `value`. Passing `undefined` makes the field uncontrolled from the first render, so later external updates (including resetting it to an empty value) are not reflected on screen.

### Alphabetic Month Tokens (MMM / MMMM)

The `displayFormat` prop supports alphabetic month tokens for more human-readable date display:

| Token  | Output                 | Example                        |
| ------ | ---------------------- | ------------------------------ |
| `MMM`  | Abbreviated month name | `Jan`, `Feb`, `Apr`            |
| `MMMM` | Full month name        | `January`, `February`, `April` |

When `displayFormat` contains `MMM` or `MMMM`, the input becomes **read-only** and the user must select dates through the calendar popup. Use the `locale` prop to control the language of month names.

```tsx
<DateRangePicker displayFormat="MMM DD, YYYY" locale="en-US" />
// → "Apr 01, 2026 - Apr 09, 2026"
```

> **Note**: DateRangePicker also accepts all Input props (e.g., `size`, `variant`, `color`, `sx`). `sx` and `className` are applied to the root element, so layout styles like `width` work as expected when DateRangePicker is a direct flex child.

## Accessibility

- The input has `role="textbox"` and the calendar button has `aria-label="Toggle Calendar"` for screen reader identification.
- **Keyboard navigation** is fully supported: use **Tab** to move between input and calendar button, **Enter/Space** to open the calendar, **Arrow Keys** to navigate dates, and **Escape** to close the popup.
- When a `label` prop is provided, the input is automatically associated with the label for assistive technologies. Always provide a `label` for form contexts.
- The calendar popup uses `role="tooltip"` with proper ARIA labeling. Date buttons announce the full date to screen readers, and range selection provides visual feedback between start and end dates.
