Repository: wojtekmaj/react-daterange-picker
Branch: main
Commit: 6f19427d70e9
Files: 48
Total size: 117.5 KB
Directory structure:
gitextract_9pvwexcp/
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ ├── ci.yml
│ ├── close-stale-issues.yml
│ └── publish.yml
├── .gitignore
├── .husky/
│ └── pre-commit
├── .vscode/
│ ├── extensions.json
│ └── settings.json
├── .yarnrc.yml
├── LICENSE
├── biome.json
├── package.json
├── packages/
│ └── react-daterange-picker/
│ ├── LICENSE
│ ├── README.md
│ ├── package.json
│ ├── src/
│ │ ├── DateRangePicker.css
│ │ ├── DateRangePicker.spec.tsx
│ │ ├── DateRangePicker.tsx
│ │ ├── index.ts
│ │ └── shared/
│ │ └── types.ts
│ ├── tsconfig.build.json
│ ├── tsconfig.json
│ └── vitest.config.ts
├── sample/
│ ├── .gitignore
│ ├── Sample.css
│ ├── Sample.tsx
│ ├── index.html
│ ├── index.tsx
│ ├── package.json
│ ├── tsconfig.json
│ └── vite.config.ts
└── test/
├── .gitignore
├── LocaleOptions.tsx
├── MaxDetailOptions.tsx
├── MinDetailOptions.tsx
├── Test.css
├── Test.tsx
├── ValidityOptions.tsx
├── ValueOptions.tsx
├── ViewOptions.tsx
├── global.d.ts
├── index.html
├── index.tsx
├── package.json
├── shared/
│ └── types.ts
├── tsconfig.json
└── vite.config.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
================================================
FILE: .github/FUNDING.yml
================================================
github: wojtekmaj
open_collective: react-date-picker
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
branches: ['*']
pull_request:
branches: [main]
env:
HUSKY: 0
jobs:
lint:
name: Static code analysis
runs-on: ubuntu-24.04-arm
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Biome
uses: biomejs/setup-biome@v2
- name: Run tests
run: biome lint
typescript:
name: Type checking
runs-on: ubuntu-24.04-arm
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Cache Yarn cache
uses: actions/cache@v5
env:
cache-name: yarn-cache
with:
path: ~/.yarn/berry/cache
key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ env.cache-name }}
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
- name: Install Corepack
run: npm install -g corepack
- name: Install dependencies
run: yarn --immutable
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: true
- name: Build package
run: yarn build
- name: Run type checking
run: yarn tsc
format:
name: Formatting
runs-on: ubuntu-24.04-arm
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Biome
uses: biomejs/setup-biome@v2
- name: Run formatting
run: biome format
unit:
name: Unit tests
runs-on: ubuntu-24.04-arm
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Cache Yarn cache
uses: actions/cache@v5
env:
cache-name: yarn-cache
with:
path: ~/.yarn/berry/cache
key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ env.cache-name }}
- name: Cache ~/.cache/ms-playwright
id: playwright-cache
uses: actions/cache@v5
env:
cache-name: playwright-cache
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }}
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
- name: Install Corepack
run: npm install -g corepack
- name: Install dependencies
run: yarn --immutable
- name: Install Playwright browsers
if: steps.playwright-cache.outputs.cache-hit != 'true'
run: yarn workspace @wojtekmaj/react-daterange-picker playwright install chromium-headless-shell
- name: Run tests
run: yarn unit
================================================
FILE: .github/workflows/close-stale-issues.yml
================================================
name: Close stale issues
on:
schedule:
- cron: '0 0 * * 1' # Every Monday
workflow_dispatch:
jobs:
close-issues:
name: Close stale issues
runs-on: ubuntu-24.04-arm
steps:
- name: Close stale issues
uses: actions/stale@v8
with:
days-before-issue-stale: 90
days-before-issue-close: 14
stale-issue-label: 'stale'
stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this issue will be closed in 14 days.'
close-issue-message: 'This issue was closed because it has been stalled for 14 days with no activity.'
exempt-issue-labels: 'fresh'
remove-issue-stale-when-updated: true
days-before-pr-stale: -1
days-before-pr-close: -1
================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish
on:
release:
types: [published]
env:
HUSKY: 0
permissions:
id-token: write
jobs:
publish:
name: Publish
runs-on: ubuntu-24.04-arm
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Cache Yarn cache
uses: actions/cache@v5
env:
cache-name: yarn-cache
with:
path: ~/.yarn/berry/cache
key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-${{ env.cache-name }}
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
registry-url: 'https://registry.npmjs.org'
- name: Install Corepack
run: npm install -g corepack
- name: Install dependencies
run: yarn --immutable
- name: Publish with latest tag
if: github.event.release.prerelease == false
run: yarn npm publish --tag latest
working-directory: packages/react-daterange-picker
- name: Publish with next tag
if: github.event.release.prerelease == true
run: yarn npm publish --tag next
working-directory: packages/react-daterange-picker
================================================
FILE: .gitignore
================================================
# OS
.DS_Store
# Cache
.cache
.playwright
.tmp
*.tsbuildinfo
.eslintcache
# Yarn
.pnp.*
**/.yarn/*
!**/.yarn/patches
!**/.yarn/plugins
!**/.yarn/releases
!**/.yarn/sdks
!**/.yarn/versions
# Project-generated directories and files
__screenshots__
coverage
dist
node_modules
playwright-report
test-results
package.tgz
# Logs
npm-debug.log
yarn-error.log
# .env files
**/.env
**/.env.*
!**/.env.example
================================================
FILE: .husky/pre-commit
================================================
yarn format --staged --no-errors-on-unmatched --write
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": ["biomejs.biome"],
"unwantedRecommendations": ["dbaeumer.jshint", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode"]
}
================================================
FILE: .vscode/settings.json
================================================
{
"editor.defaultFormatter": "biomejs.biome",
"editor.formatOnSave": true,
"search.exclude": {
"**/.yarn": true
}
}
================================================
FILE: .yarnrc.yml
================================================
enableHardenedMode: false
enableScripts: false
logFilters:
- code: YN0076
level: discard
nodeLinker: node-modules
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018–2026 Wojciech Maj
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: biome.json
================================================
{
"$schema": "https://biomejs.dev/schemas/2.4.10/schema.json",
"files": {
"includes": [
"**",
"!**/.yarn",
"!**/coverage",
"!**/dist",
"!**/.pnp.cjs",
"!**/.pnp.loader.mjs"
]
},
"assist": {
"actions": {
"source": {
"organizeImports": {
"level": "on",
"options": {
"groups": [
{ "type": false, "source": ":NODE:" },
{ "type": false, "source": ["vitest", "vitest/**", "@vitest/**", "vitest-*"] },
{ "type": false, "source": ["react", "react-dom", "react-dom/**", "react-native"] },
{ "type": false, "source": [":PACKAGE:"] },
":BLANK_LINE:",
{
"type": false,
"source": [
":PATH:",
"!**/hooks/*",
"!**/use*.js",
"!**/shared/*",
"!**/utils/*",
"!**/__mocks__/*",
"!**/test-utils.js"
]
},
":BLANK_LINE:",
{ "type": false, "source": ["**/hooks/*", "**/use*.js"] },
":BLANK_LINE:",
{ "type": false, "source": ["**/shared/*", "**/utils/*"] },
":BLANK_LINE:",
{ "type": false, "source": "**/__mocks__/*" },
":BLANK_LINE:",
{ "type": false, "source": "**/test-utils.js" },
":BLANK_LINE:",
":NODE:",
":PACKAGE:",
":PATH:"
]
}
}
}
}
},
"formatter": {
"lineWidth": 100,
"indentStyle": "space"
},
"linter": {
"rules": {
"complexity": {
"noUselessSwitchCase": "off"
},
"correctness": {
"noUnusedImports": "warn",
"noUnusedVariables": {
"level": "warn",
"options": {
"ignoreRestSiblings": true
}
}
},
"suspicious": {
"noConsole": "warn"
}
}
},
"css": {
"formatter": {
"quoteStyle": "single"
}
},
"javascript": {
"formatter": {
"quoteStyle": "single"
}
},
"overrides": [
{
"includes": ["**/vite.config.ts"],
"linter": {
"rules": {
"suspicious": {
"noConsole": "off"
}
}
}
}
]
}
================================================
FILE: package.json
================================================
{
"name": "@wojtekmaj/react-daterange-picker-monorepo",
"version": "1.0.0",
"description": "@wojtekmaj/react-daterange-picker monorepo",
"type": "module",
"workspaces": [
"packages/*",
"test"
],
"scripts": {
"build": "yarn workspace @wojtekmaj/react-daterange-picker build",
"dev": "yarn workspace @wojtekmaj/react-daterange-picker watch & yarn workspace test dev",
"format": "yarn workspaces foreach --all run format",
"lint": "yarn workspaces foreach --all run lint",
"postinstall": "husky",
"test": "yarn workspaces foreach --all run test",
"tsc": "yarn workspaces foreach --all run tsc",
"unit": "yarn workspaces foreach --all run unit"
},
"devDependencies": {
"husky": "^9.0.0"
},
"packageManager": "yarn@4.10.3"
}
================================================
FILE: packages/react-daterange-picker/LICENSE
================================================
MIT License
Copyright (c) 2018–2026 Wojciech Maj
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: packages/react-daterange-picker/README.md
================================================
[](https://www.npmjs.com/package/@wojtekmaj/react-daterange-picker)  [](https://github.com/wojtekmaj/react-daterange-picker/actions)
# React-DateRange-Picker
A date range picker for your React app.
- Pick days, months, years, or even decades
- Supports virtually any language
- No moment.js needed
## tl;dr
- Install by executing `npm install @wojtekmaj/react-daterange-picker` or `yarn add @wojtekmaj/react-daterange-picker`.
- Import by adding `import DateRangePicker from '@wojtekmaj/react-daterange-picker'`.
- Use by adding ``. Use `onChange` prop for getting new values.
## Demo
A minimal demo page can be found in `sample` directory.
[Online demo](https://projects.wojtekmaj.pl/react-daterange-picker/) is also available!
## Consider native alternative
If you don't need to support legacy browsers and don't need the advanced features this package provides, consider using native date input instead. It's more accessible, adds no extra weight to your bundle, and works better on mobile devices.
```tsx
```
## Looking for a time picker or a datetime picker?
React-DateRange-Picker will play nicely with [React-Date-Picker](https://github.com/wojtekmaj/react-date-picker), [React-Time-Picker](https://github.com/wojtekmaj/react-time-picker) and [React-DateTime-Picker](https://github.com/wojtekmaj/react-datetime-picker). Check them out!
## Getting started
### Compatibility
Your project needs to use React 16.3 or later. If you use an older version of React, please refer to the table below to find a suitable React-DateRange-Picker version.
| React version | Newest compatible React-DateRange-Picker version |
| ------------- | ------------------------------------------------ |
| ≥16.8 | latest |
| ≥16.3 | 4.x |
| ≥16.0 | 2.x |
[React-Calendar](https://github.com/wojtekmaj/react-calendar), on which React-DateRange-Picker relies heavily, uses modern web technologies. That's why it's so fast, lightweight and easy to style. This, however, comes at a cost of [supporting only modern browsers](https://caniuse.com/#feat=internationalization).
### Installation
Add React-DateRange-Picker to your project by executing `npm install @wojtekmaj/react-daterange-picker` or `yarn add @wojtekmaj/react-daterange-picker`.
### Usage
Here's an example of basic usage:
```tsx
import { useState } from 'react';
import DateRangePicker from '@wojtekmaj/react-daterange-picker';
type ValuePiece = Date | null;
type Value = ValuePiece | [ValuePiece, ValuePiece];
function MyApp() {
const [value, onChange] = useState([new Date(), new Date()]);
return (
);
}
```
### Custom styling
If you want to use default React-DateRange-Picker and React-Calendar styling to build upon it, you can import them by using:
```ts
import '@wojtekmaj/react-daterange-picker/dist/DateRangePicker.css';
import 'react-calendar/dist/Calendar.css';
```
## User guide
### DateRangePicker
Displays an input field complete with custom inputs, native input, and a calendar.
#### Props
| Prop name | Description | Default value | Example values |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| autoFocus | Automatically focuses the input on mount. | n/a | `true` |
| calendarAriaLabel | `aria-label` for the calendar button. | n/a | `"Toggle calendar"` |
| calendarProps | Props to pass to React-Calendar component. | n/a | See [React-Calendar documentation](https://github.com/wojtekmaj/react-calendar) |
| calendarIcon | Content of the calendar button. Setting the value explicitly to `null` will hide the icon. | (default icon) |
String: `"Calendar"`
React element: ``
React function: `CalendarIcon`
|
| className | Class name(s) that will be added along with `"react-daterange-picker"` to the main React-DateRange-Picker `
` element. | n/a |
String: `"class1 class2"`
Array of strings: `["class1", "class2 class3"]`
|
| clearAriaLabel | `aria-label` for the clear button. | n/a | `"Clear value"` |
| clearIcon | Content of the clear button. Setting the value explicitly to `null` will hide the icon. | (default icon) |
String: `"Clear"`
React element: ``
React function: `ClearIcon`
|
| closeCalendar | Whether to close the calendar on value selection. **Note**: It's recommended to use `shouldCloseCalendar` function instead. | `true` | `false` |
| data-testid | `data-testid` attribute for the main React-DateRange-Picker `
` element. | n/a | `"daterange-picker"` |
| dayAriaLabel | `aria-label` for the day input. | n/a | `"Day"` |
| dayPlaceholder | `placeholder` for the day input. | `"--"` | `"dd"` |
| disableCalendar | When set to `true`, will remove the calendar and the button toggling its visibility. | `false` | `true` |
| disabled | Whether the date range picker should be disabled. | `false` | `true` |
| format | Input format based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). Supported values are: `y`, `M`, `MM`, `MMM`, `MMMM`, `d`, `dd`. **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. | n/a | `"y-MM-dd"` |
| id | `id` attribute for the main React-DateRange-Picker `
` element. | n/a | `"daterange-picker"` |
| isOpen | Whether the calendar should be opened. | `false` | `true` |
| locale | Locale that should be used by the date range picker and the calendar. Can be any [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag). **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. | Server locale/User's browser settings | `"hu-HU"` |
| maxDate | Maximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although React-DateRange-Picker will ensure that no later date is selected. | n/a | Date: `new Date()` |
| maxDetail | The most detailed calendar view that the user shall see. View defined here also becomes the one on which clicking an item in the calendar will select a date and pass it to onChange. Can be `"month"`, `"year"`, `"decade"` or `"century"`. | `"month"` | `"year"` |
| minDate | Minimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although React-DateRange-Picker will ensure that no earlier date is selected. | n/a | Date: `new Date()` |
| monthAriaLabel | `aria-label` for the month input. | n/a | `"Month"` |
| monthPlaceholder | `placeholder` for the month input. | `"--"` | `"mm"` |
| name | Input name prefix. Date from/Date to fields will be named `"yourprefix_from"` and `"yourprefix_to"` respectively. | `"daterange"` | `"myCustomName"` |
| nativeInputAriaLabel | `aria-label` for the native date input. | n/a | `"Date"` |
| onCalendarClose | Function called when the calendar closes. | n/a | `() => alert('Calendar closed')` |
| onCalendarOpen | Function called when the calendar opens. | n/a | `() => alert('Calendar opened')` |
| onChange | Function called when the user picks a valid date. If any of the fields were excluded using custom `format`, `new Date(y, 0, 1, 0, 0, 0)`, where `y` is the current year, is going to serve as a "base". | n/a | `(value) => alert('New date is: ', value)` |
| onFocus | Function called when the user focuses an input. | n/a | `(event) => alert('Focused input: ', event.target.name)` |
| onInvalidChange | Function called when the user picks an invalid date. | n/a | `() => alert('Invalid date')` |
| openCalendarOnFocus | Whether to open the calendar on input focus. **Note**: It's recommended to use `shouldOpenCalendar` function instead. | `true` | `false` |
| portalContainer | Element to render the calendar in using portal. | n/a | `document.getElementById('my-div')` |
| rangeDivider | Divider between date inputs. | `"–"` | `" to "` |
| required | Whether date input should be required. | `false` | `true` |
| shouldCloseCalendar | Function called before the calendar closes. `reason` can be `"buttonClick"`, `"escape"`, `"outsideAction"`, or `"select"`. If it returns `false`, the calendar will not close. | n/a | `({ reason }) => reason !== 'outsideAction'` |
| shouldOpenCalendar | Function called before the calendar opens. `reason` can be `"buttonClick"` or `"focus"`. If it returns `false`, the calendar will not open. | n/a | `({ reason }) => reason !== 'focus'` |
| showLeadingZeros | Whether leading zeros should be rendered in date inputs. | `false` | `true` |
| value | Input value. | n/a |
Date: `new Date(2017, 0, 1)`
String: `"2017-01-01"`
An array of dates: `[new Date(2017, 0, 1), new Date(2017, 7, 1)]`
An array of strings: `["2017-01-01", "2017-08-01"]`
|
| yearAriaLabel | `aria-label` for the year input. | n/a | `"Year"` |
| yearPlaceholder | `aria-label` for the year input. | `"----"` | `"yyyy"` |
### Calendar
DateRangePicker component passes all props to React-Calendar, with the exception of `className` (you can use `calendarClassName` for that instead). There are tons of customizations you can do! For more information, see [Calendar component props](https://github.com/wojtekmaj/react-calendar#props).
## License
The MIT License.
## Author
` element.
*
* @example 'class1 class2'
* @example ['class1', 'class2 class3']
*/
className?: ClassName;
/**
* `aria-label` for the clear button.
*
* @example 'Clear value'
*/
clearAriaLabel?: string;
/**
* Content of the clear button. Setting the value explicitly to `null` will hide the icon.
*
* @example 'Clear'
* @example
* @example ClearIcon
*/
clearIcon?: IconOrRenderFunction | null;
/**
* Whether to close the calendar on value selection.
*
* **Note**: It's recommended to use `shouldCloseCalendar` function instead.
*
* @default true
* @example false
*/
closeCalendar?: boolean;
/**
* `data-testid` attribute for the main React-DateRange-Picker `
` element.
*
* @example 'daterange-picker'
*/
'data-testid'?: string;
/**
* `aria-label` for the day input.
*
* @example 'Day'
*/
dayAriaLabel?: string;
/**
* `placeholder` for the day input.
*
* @default '--'
* @example 'dd'
*/
dayPlaceholder?: string;
/**
* When set to `true`, will remove the calendar and the button toggling its visibility.
*
* @default false
* @example true
*/
disableCalendar?: boolean;
/**
* Whether the date range picker should be disabled.
*
* @default false
* @example true
*/
disabled?: boolean;
/**
* Input format based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). Supported values are: `y`, `M`, `MM`, `MMM`, `MMMM`, `d`, `dd`.
*
* **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client.
*
* @example 'y-MM-dd'
*/
format?: string;
/**
* `id` attribute for the main React-DateRange-Picker `
` element.
*
* @example 'daterange-picker'
*/
id?: string;
/**
* Whether the calendar should be opened.
*
* @default false
* @example true
*/
isOpen?: boolean;
/**
* Locale that should be used by the date range picker and the calendar. Can be any [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag).
*
* **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client.
*
* @example 'hu-HU'
*/
locale?: string;
/**
* Maximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although React-DateRange-Picker will ensure that no later date is selected.
*
* @example new Date()
*/
maxDate?: Date;
/**
* The most detailed calendar view that the user shall see. View defined here also becomes the one on which clicking an item in the calendar will select a date and pass it to onChange. Can be `"month"`, `"year"`, `"decade"` or
*
* @default 'month'
* @example 'year'
*/
maxDetail?: Detail;
/**
* Minimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although React-DateRange-Picker will ensure that no earlier date is selected.
*
* @example new Date()
*/
minDate?: Date;
/**
* `aria-label` for the month input.
*
* @example 'Month'
*/
monthAriaLabel?: string;
/**
* `placeholder` for the month input.
*
* @default '--'
* @example 'mm'
*/
monthPlaceholder?: string;
/**
* Input name.
*
* @default 'daterange'
*/
name?: string;
/**
* `aria-label` for the native date input.
*
* @example 'Date'
*/
nativeInputAriaLabel?: string;
/**
* Function called when the calendar closes.
*
* @example () => alert('Calendar closed')
*/
onCalendarClose?: () => void;
/**
* Function called when the calendar opens.
*
* @example () => alert('Calendar opened')
*/
onCalendarOpen?: () => void;
/**
* Function called when the user picks a valid date. If any of the fields were excluded using custom `format`, `new Date(y, 0, 1, 0, 0, 0)`, where `y` is the current year, is going to serve as a "base".
*
* @example (value) => alert('New date is: ', value)
*/
onChange?: (value: Value) => void;
/**
* Function called when the user focuses an input.
*
* @example (event) => alert('Focused input: ', event.target.name)
*/
onFocus?: (event: React.FocusEvent) => void;
/**
* Function called when the user picks an invalid date.
*
* @example () => alert('Invalid date')
*/
onInvalidChange?: () => void;
/**
* Whether to open the calendar on input focus. **Note**: It's recommended to use `shouldOpenCalendar` function instead.
*
* @default true
* @example false
*/
openCalendarOnFocus?: boolean;
/**
* Element to render the calendar in using portal.
*
* @example document.getElementById('my-div')
*/
portalContainer?: HTMLElement | null;
/**
* Divider between date inputs.
*
* @default '–'
* @example ' to '
*/
rangeDivider?: React.ReactNode;
/**
* Whether date input should be required.
*
* @default false
* @example true
*/
required?: boolean;
/**
* Function called before the calendar closes. `reason` can be `"buttonClick"`, `"escape"`, `"outsideAction"`, or `"select"`. If it returns `false`, the calendar will not close.
*
* @example ({ reason }) => reason !== 'outsideAction'
*/
shouldCloseCalendar?: (props: { reason: CloseReason }) => boolean;
/**
* Function called before the calendar opens. `reason` can be `"buttonClick"` or `"focus"`. If it returns `false`, the calendar will not open.
*
* @example ({ reason }) => reason !== 'focus'
*/
shouldOpenCalendar?: (props: { reason: OpenReason }) => boolean;
/**
* Whether leading zeros should be rendered in date inputs.
*
* @default false
* @example true
*/
showLeadingZeros?: boolean;
/**
* Input value.
*
* @example new Date(2017, 0, 1)
* @example [new Date(2017, 0, 1), new Date(2017, 7, 1)]
* @example ['2017-01-01', '2017-08-01']
*/
value?: LooseValue;
/**
* `aria-label` for the year input.
*
* @example 'Year'
*/
yearAriaLabel?: string;
/**
* `placeholder` for the year input.
*
* @default '----'
* @example 'yyyy'
*/
yearPlaceholder?: string;
} & Omit;
export default function DateRangePicker(props: DateRangePickerProps): React.ReactElement {
const {
autoFocus,
calendarAriaLabel,
calendarIcon = CalendarIcon,
className,
clearAriaLabel,
clearIcon = ClearIcon,
closeCalendar: shouldCloseCalendarOnSelect = true,
'data-testid': dataTestid,
dayAriaLabel,
dayPlaceholder,
disableCalendar,
disabled,
format,
id,
isOpen: isOpenProps = null,
locale,
maxDate,
maxDetail = 'month',
minDate,
monthAriaLabel,
monthPlaceholder,
name = 'daterange',
nativeInputAriaLabel,
onCalendarClose,
onCalendarOpen,
onChange: onChangeProps,
onFocus: onFocusProps,
onInvalidChange,
openCalendarOnFocus = true,
rangeDivider = '–',
required,
shouldCloseCalendar,
shouldOpenCalendar,
showLeadingZeros,
value,
yearAriaLabel,
yearPlaceholder,
...otherProps
} = props;
const [isOpen, setIsOpen] = useState(isOpenProps);
const wrapper = useRef(null);
const calendarWrapper = useRef(null);
useEffect(() => {
setIsOpen(isOpenProps);
}, [isOpenProps]);
function openCalendar({ reason }: { reason: OpenReason }) {
if (shouldOpenCalendar) {
if (!shouldOpenCalendar({ reason })) {
return;
}
}
setIsOpen(true);
if (onCalendarOpen) {
onCalendarOpen();
}
}
const closeCalendar = useCallback(
({ reason }: { reason: CloseReason }) => {
if (shouldCloseCalendar) {
if (!shouldCloseCalendar({ reason })) {
return;
}
}
setIsOpen(false);
if (onCalendarClose) {
onCalendarClose();
}
},
[onCalendarClose, shouldCloseCalendar],
);
function toggleCalendar() {
if (isOpen) {
closeCalendar({ reason: 'buttonClick' });
} else {
openCalendar({ reason: 'buttonClick' });
}
}
function onChange(value: Value, shouldCloseCalendar: boolean = shouldCloseCalendarOnSelect) {
if (shouldCloseCalendar) {
closeCalendar({ reason: 'select' });
}
if (onChangeProps) {
onChangeProps(value);
}
}
function onChangeFrom(nextValue: Value, closeCalendar: boolean) {
const [nextValueFrom] = Array.isArray(nextValue) ? nextValue : [nextValue];
const [, valueTo] = Array.isArray(value) ? value : [value];
const valueToDate = valueTo ? new Date(valueTo) : null;
onChange([nextValueFrom, valueToDate], closeCalendar);
}
function onChangeTo(nextValue: Value, closeCalendar: boolean) {
const [, nextValueTo] = Array.isArray(nextValue) ? nextValue : [null, nextValue];
const [valueFrom] = Array.isArray(value) ? value : [value];
const valueFromDate = valueFrom ? new Date(valueFrom) : null;
onChange([valueFromDate, nextValueTo], closeCalendar);
}
function onFocus(event: React.FocusEvent) {
if (onFocusProps) {
onFocusProps(event);
}
if (
// Internet Explorer still fires onFocus on disabled elements
disabled ||
isOpen ||
!openCalendarOnFocus ||
event.target.dataset.select === 'true'
) {
return;
}
openCalendar({ reason: 'focus' });
}
const onKeyDown = useCallback(
(event: KeyboardEvent) => {
if (event.key === 'Escape') {
closeCalendar({ reason: 'escape' });
}
},
[closeCalendar],
);
function clear() {
onChange(null);
}
function stopPropagation(event: React.FocusEvent) {
event.stopPropagation();
}
const onOutsideAction = useCallback(
(event: Event) => {
const { current: wrapperEl } = wrapper;
const { current: calendarWrapperEl } = calendarWrapper;
// Try event.composedPath first to handle clicks inside a Shadow DOM.
const target = (
'composedPath' in event ? event.composedPath()[0] : (event as Event).target
) as HTMLElement;
if (
target &&
wrapperEl &&
!wrapperEl.contains(target) &&
!calendarWrapperEl?.contains(target)
) {
closeCalendar({ reason: 'outsideAction' });
}
},
[closeCalendar],
);
const handleOutsideActionListeners = useCallback(
(shouldListen = isOpen) => {
for (const event of outsideActionEvents) {
if (shouldListen) {
document.addEventListener(event, onOutsideAction);
} else {
document.removeEventListener(event, onOutsideAction);
}
}
if (shouldListen) {
document.addEventListener('keydown', onKeyDown);
} else {
document.removeEventListener('keydown', onKeyDown);
}
},
[isOpen, onOutsideAction, onKeyDown],
);
// biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on isOpen change
useEffect(() => {
handleOutsideActionListeners();
return () => {
handleOutsideActionListeners(false);
};
}, [handleOutsideActionListeners, isOpen]);
function renderInputs() {
const [valueFrom, valueTo] = Array.isArray(value) ? value : [value];
const ariaLabelProps = {
dayAriaLabel,
monthAriaLabel,
nativeInputAriaLabel,
yearAriaLabel,
};
const placeholderProps = {
dayPlaceholder,
monthPlaceholder,
yearPlaceholder,
};
const commonProps = {
...ariaLabelProps,
...placeholderProps,
className: `${baseClassName}__inputGroup`,
disabled,
format,
isCalendarOpen: isOpen,
locale,
maxDate,
maxDetail,
minDate,
onInvalidChange,
required,
showLeadingZeros,
};
return (