### Static Ranges Creation Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Shows how to create static ranges using the `createStaticRanges` utility. This example defines a 'Today' range using date-fns for precise start and end of day calculations.
```javascript
import { createStaticRanges } from 'react-date-range';
import { startOfDay, endOfDay } from 'date-fns';
const staticRanges = createStaticRanges([
{
label: 'Today',
range: () => ({
startDate: startOfDay(new Date()),
endDate: endOfDay(new Date()),
}),
},
]);
```
--------------------------------
### Install react-date-range
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Install the react-date-range library along with its peer dependency date-fns. Ensure you have React installed as well.
```bash
npm install react-date-range date-fns
```
--------------------------------
### Preview Object Usage Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Example of defining a `preview` object and passing it to the `Calendar` component. This sets a specific date range and color for preview highlights.
```javascript
const preview = {
startDate: new Date(2024, 0, 1),
endDate: new Date(2024, 0, 15),
color: '#3d91ff',
};
```
--------------------------------
### Minimal Calendar Setup
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/configuration.md
Use this for a basic calendar display with no additional configurations.
```javascript
```
--------------------------------
### Install react-date-range
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Install the react-date-range package using npm. This plugin requires react and date-fns as peer dependencies, which also need to be installed.
```bash
npm install --save react-date-range
npm install --save react date-fns
```
--------------------------------
### Install react-date-range with npm
Source: https://github.com/hypeserver/react-date-range/blob/master/demo/README.md
Use this command to add the react-date-range library to your project dependencies.
```bash
npm install react-date-range
```
--------------------------------
### Dynamic Range Generation with InputRangeField
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/inputrangefield.md
Shows how to dynamically generate date ranges using InputRangeField. This example defines custom input ranges with labels, range generation logic, and methods to get the current value based on a date range.
```javascript
import { addDays, differenceInCalendarDays, endOfDay, startOfDay } from 'date-fns';
const inputRanges = [
{
label: 'days up to today',
range: (value) => ({
startDate: addDays(startOfDay(new Date()), -value + 1),
endDate: endOfDay(new Date()),
}),
getCurrentValue: (range) => {
if (!range.endDate) return '∞';
if (!range.startDate) return '∞';
return String(differenceInCalendarDays(range.endDate, range.startDate) + 1);
},
},
{
label: 'days starting today',
range: (value) => ({
startDate: new Date(),
endDate: addDays(new Date(), value - 1),
}),
getCurrentValue: (range) => {
if (!range.startDate) return '∞';
return String(differenceInCalendarDays(range.endDate, range.startDate) + 1);
},
},
];
// Use in DefinedRange
```
--------------------------------
### Range Object Usage Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Illustrates how to create and populate a Range object for a date selection.
```javascript
const range = {
startDate: new Date(2024, 0, 1),
endDate: new Date(2024, 0, 31),
key: 'january',
color: '#3d91ff',
};
```
--------------------------------
### startDatePlaceholder
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Placeholder text for the start date input field.
```APIDOC
## startDatePlaceholder
### Description
Placeholder text for the start date input field.
### Type
String
### Default
`'Early'`
```
--------------------------------
### Date Display Format Examples
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/dateinput.md
Demonstrates various format strings for displaying dates in the DateInput component using date-fns tokens.
```javascript
"MMM d, yyyy" → Jan 15, 2024
```
```javascript
"yyyy-MM-dd" → 2024-01-15
```
```javascript
"dd/MM/yyyy" → 15/01/2024
```
```javascript
"EEEE, MMMM d" → Monday, January 15
```
--------------------------------
### InputRange Usage Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Example of defining an `inputRanges` array. This specific range calculates dates based on the last N days provided by the user. Ensure `addDays` and `differenceInDays` functions are available.
```javascript
const inputRanges = [
{
label: 'Last N days',
range: (value) => ({
startDate: addDays(new Date(), -value + 1),
endDate: new Date(),
}),
getCurrentValue: (range) => {
return differenceInDays(range.endDate, range.startDate) + 1;
},
},
];
```
--------------------------------
### Get Month Display Range with Padding
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/utility-functions.md
Calculates the start and end dates for displaying a month's calendar, including padding to align with the week's start and end days. Useful for ensuring consistent calendar height.
```javascript
import { getMonthDisplayRange } from 'react-date-range/dist/utils';
const displayRange = getMonthDisplayRange(
new Date(2024, 0, 15), // January 15, 2024
{ locale: enUS },
false
);
// Returns display range for January, including padding for week alignment
```
--------------------------------
### Default Input Ranges
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/inputrangefield.md
Provides predefined input ranges for common date selections like 'days up to today' and 'days starting today'. These ranges include logic for calculating start and end dates and for retrieving the current value based on a given range.
```javascript
export const defaultInputRanges = [
{
label: 'days up to today',
range(value) {
return {
startDate: addDays(defineds.startOfToday, (Math.max(Number(value), 1) - 1) * -1),
endDate: defineds.endOfToday,
};
},
getCurrentValue(range) {
if (!isSameDay(range.endDate, defineds.endOfToday)) return '-';
if (!range.startDate) return '∞';
return differenceInCalendarDays(defineds.endOfToday, range.startDate) + 1;
},
},
{
label: 'days starting today',
range(value) {
const today = new Date();
return {
startDate: today,
endDate: addDays(today, Math.max(Number(value), 1) - 1),
};
},
getCurrentValue(range) {
if (!isSameDay(range.startDate, defineds.startOfToday)) return '-';
if (!range.endDate) return '∞';
return differenceInCalendarDays(range.endDate, defineds.startOfToday) + 1;
},
},
];
```
--------------------------------
### Date Range Mode - Start Edge
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daycell.md
When `displayMode` is 'dateRange', the start edge of a selected range is visually indicated. This styling applies to the first day of the selected range.
```plaintext
┌───┐
│S 1│ ← startDate of range
└─┬─┘
└─── Continues to endDate
```
--------------------------------
### Month Component Structure Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/month.md
Illustrates the visual structure of the Month component, including the month name header, weekday header, and day cells. This is a visual representation and not executable code.
```text
┌─────────────────────────────┐
│ January 2024 │ ← monthName (if showMonthName)
├─────────────────────────────┤
│ Sun Mon Tue Wed Thu Fri Sat │ ← weekDays (if showWeekDays)
├─────────────────────────────┤
│ 31 1 2 3 4 5 6 │ ← Day cells
│ 7 8 9 10 11 12 13 │
│ 14 15 16 17 18 19 20 │
│ 21 22 23 24 25 26 27 │
│ 28 29 30 31 1 2 3 │ ← 31 is from previous month
└─────────────────────────────┘
```
--------------------------------
### Direct Month Component Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/month.md
Demonstrates how to directly use the Month component for advanced customization. Ensure necessary imports like Month and coreStyles are included. This example shows how to configure various props for displaying a specific month with date ranges and custom styles.
```javascript
import Month from 'react-date-range/dist/components/Month';
import coreStyles from 'react-date-range/dist/styles';
function MyMonthDisplay() {
const dateOptions = { locale: enUS };
const styles = coreStyles;
return (
false}
minDate={new Date(2020, 0, 1)}
maxDate={new Date(2030, 11, 31)}
showWeekDays={true}
showMonthName={true}
showPreview={true}
displayMode="dateRange"
focusedRange={[0, 0]}
onDragSelectionStart={() => {}}
onDragSelectionEnd={() => {}}
onDragSelectionMove={() => {}}
onMouseLeave={() => {}}
monthDisplayFormat="MMMM yyyy"
weekdayDisplayFormat="E"
dayDisplayFormat="d"
styles={styles}
color="#3d91ff"
fixedHeight={false}
/>
);
}
```
--------------------------------
### Render Custom Day Content
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Allows for custom rendering of day cells in the calendar. This example shows displaying the day number and marking holidays.
```javascript
(
{format(date, 'd')}
{isHoliday(date) &&
*}
)}
/>
```
--------------------------------
### DateInput in Date Range Context
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/dateinput.md
Demonstrates using DateInput within a date range context, specifically for the start date input. It shows how to pass relevant props like `value`, `onChange`, `onFocus`, `dateDisplayFormat`, and `readOnly`.
```javascript
updateRange({...range, startDate: newStartDate})}
onFocus={() => setFocusedRange([0, 0])}
dateDisplayFormat="MMM d, yyyy"
dateOptions={dateOptions}
placeholder="Early"
readOnly={!editableDateInputs}
ariaLabel="Start date input"
className="start-date-input"
/>
```
--------------------------------
### Basic Calendar Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/calendar.md
Demonstrates how to use the Calendar component to select a single date. Ensure you import the necessary CSS styles for proper rendering. This example sets a min and max date, disables a specific date, and enables drag selection.
```javascript
import React, { useState } from 'react';
import { Calendar } from 'react-date-range';
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';
function MyComponent() {
const [selectedDate, setSelectedDate] = useState(new Date());
return (
setSelectedDate(date)}
minDate={new Date(2020, 0, 1)}
maxDate={new Date(2030, 11, 31)}
months={1}
direction="vertical"
disabledDates={[new Date(2024, 6, 4)]}
dragSelectionEnabled={true}
editableDateInputs={false}
/>
);
}
export default MyComponent;
```
--------------------------------
### weekStartsOn
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Overrides the default week start day from the locale. If no locale is specified, the default is enUS.
```APIDOC
## weekStartsOn
### Description
Overrides the default week start day from the locale. If no locale is specified, the default is enUS.
### Type
Number
```
--------------------------------
### Static Range with Custom Label Rendering
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/definedrange.md
Renders a static range with custom styling for its label. This example shows how to enable custom rendering and define a function to format the label, making it bold and blue.
```javascript
const staticRangesWithCustom = createStaticRanges([
{
label: 'Q1 2024',
range: () => ({
startDate: new Date(2024, 0, 1),
endDate: new Date(2024, 2, 31),
}),
hasCustomRendering: true, // Enable custom rendering
},
]);
(
{staticRange.label}
)}
/>;
```
--------------------------------
### Read-Only DateInput Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/dateinput.md
Shows how to configure the DateInput component for read-only display. The `readOnly` prop is set to true, preventing user edits and displaying the formatted date.
```javascript
{}}
onFocus={() => {}}
dateDisplayFormat="MMM d, yyyy"
placeholder="Select date"
readOnly={true}
/>
```
--------------------------------
### Preview Object Type
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Defines the structure for a preview object, containing start and end dates and an optional color.
```javascript
{
startDate: Date,
endDate: Date,
color?: string,
}
```
--------------------------------
### Preview Object
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
An optional object that defines a preview range, typically shown during drag or hover interactions. It specifies the start and end dates of the preview, and an optional color for highlighting.
```APIDOC
## Preview Object
An optional preview range shown during drag or hover interactions.
**Type Definition:**
```javascript
{
startDate: Date,
endDate: Date,
color?: string,
}
```
**Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `startDate` | `Date` | Start of the preview range |
| `endDate` | `Date` | End of the preview range |
| `color` | `string` | Color for the preview highlight |
**Usage:**
```javascript
const preview = {
startDate: new Date(2024, 0, 1),
endDate: new Date(2024, 0, 15),
color: '#3d91ff',
};
```
```
--------------------------------
### Input Validation Examples
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/inputrangefield.md
Demonstrates how the InputRangeField component validates and clamps user input to the range [0, 99999]. Invalid inputs default to 0.
```javascript
// User types: "abc" → calls onChange(0)
// User types: "-50" → calls onChange(0)
// User types: "999999" → calls onChange(99999)
// User types: "42" → calls onChange(42)
```
--------------------------------
### getMonthDisplayRange(date, dateOptions, fixedHeight)
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/utility-functions.md
Calculates the start and end dates for rendering a month's calendar display, including padding to align with week boundaries. It ensures that the displayed range correctly spans full weeks.
```APIDOC
## getMonthDisplayRange(date, dateOptions, fixedHeight)
### Description
Calculates the start and end dates for rendering a month's calendar display, including padding for week alignment. This ensures that the calendar view always displays complete weeks, even if the month starts or ends mid-week.
### Signature
```javascript
getMonthDisplayRange(date: Date, dateOptions: Object, fixedHeight?: boolean)
=> {start: Date, end: Date, startDateOfMonth: Date, endDateOfMonth: Date}
```
### Parameters
#### Path Parameters
- **date** (`Date`) - Required - Any date within the target month.
- **dateOptions** (`Object`) - Required - Options object with `locale` and optional `weekStartsOn` from date-fns.
- **fixedHeight** (`boolean`) - Optional - If true, ensures at least 6 weeks are shown (for fixed calendar height).
### Returns
- **Object** - An object containing:
- `start`: The start date for the calendar display (may be from the previous month).
- `end`: The end date for the calendar display (may be in the next month).
- `startDateOfMonth`: The first day of the month.
- `endDateOfMonth`: The last day of the month.
### Description
The calendar typically shows weeks that overlap month boundaries. This function returns the actual display range, padded to start on the week start day and end on the week end day.
### Example
```javascript
import { getMonthDisplayRange } from 'react-date-range/dist/utils';
const displayRange = getMonthDisplayRange(
new Date(2024, 0, 15), // January 15, 2024
{ locale: enUS },
false
);
// Returns display range for January, including padding for week alignment
```
```
--------------------------------
### DayCell Selection Placeholder Rendering Logic
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daycell.md
This JavaScript code describes the logic for rendering selection placeholders for date ranges. It identifies the start, end, and days within a selected range to apply appropriate styling.
```javascript
renderSelectionPlaceholders() {
// For each range, determines:
// - startEdge: first day of range
// - endEdge: last day of range
// - inRange: days within range
// Renders colored spans for each state
}
```
--------------------------------
### Using Default Input Ranges in DateRangePicker
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/utility-functions.md
Utilize `defaultInputRanges` to enable relative date selections based on user input, such as 'days up to today' or 'days starting today'. Import `DateRangePicker` and `defaultInputRanges`.
```javascript
import { DateRangePicker, defaultInputRanges } from 'react-date-range';
```
--------------------------------
### Editable DateInput Example
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/dateinput.md
Illustrates an editable DateInput component. The `readOnly` prop is set to false, allowing users to type dates directly into the input field. The `dateDisplayFormat` is set to 'yyyy-MM-dd'.
```javascript
setSelectedDate(date)}
onFocus={() => console.log('Focused')}
dateDisplayFormat="yyyy-MM-dd"
placeholder="YYYY-MM-DD"
readOnly={false}
/>
```
--------------------------------
### retainEndDateOnFirstSelection
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Retains the end date when the start date is changed, unless the start date is later than the end date. This option is ignored if `moveRangeOnFirstSelection` is set to true.
```APIDOC
## retainEndDateOnFirstSelection
### Description
Retains the end date when the start date is changed, unless the start date is later than the end date. This option is ignored if `moveRangeOnFirstSelection` is set to true.
### Type
Boolean
### Default
`false`
```
--------------------------------
### Date Range Validation with date-fns
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Validate selected date ranges before use. This function checks if start and end dates are valid and if the start date is not after the end date.
```javascript
import { isValid, isBefore, isAfter } from 'date-fns';
const isValidRange = (startDate, endDate) => {
return (
startDate && endDate &&
isValid(startDate) && isValid(endDate) &&
!isAfter(startDate, endDate)
);
};
```
--------------------------------
### DateInput Component Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/dateinput.md
Demonstrates how to import and use the DateInput component with its available props.
```APIDOC
## DateInput Component
The `DateInput` component renders an editable or read-only date input field with format validation. It handles parsing user input, formatting display values, and provides visual feedback for invalid dates.
### Import
```javascript
import DateInput from 'react-date-range/dist/components/DateInput';
```
### Component Signature
```javascript
void}
onFocus={() => void}
dateDisplayFormat={string}
dateOptions={{locale: Object, weekStartsOn?: number}}
placeholder={string}
disabled={boolean}
readOnly={boolean}
ariaLabel={string}
className={string}
/>
```
### Props Reference
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `value` | `Date` | No | — | The date value to display |
| `onChange` | `(date: Date) => void` | Yes | — | Called with parsed date when valid input confirmed |
| `onFocus` | `() => void` | Yes | — | Called when input receives focus |
| `dateDisplayFormat` | `string` | No | `'MMM D, YYYY'` | date-fns format string for display and parsing |
| `dateOptions` | `Object` | No | — | Object with `locale` and optional `weekStartsOn` |
| `placeholder` | `string` | No | — | Placeholder text when empty |
| `disabled` | `boolean` | No | `false` | Whether the input is disabled |
| `readOnly` | `boolean` | No | `true` | Whether the input is read-only (not editable) |
| `ariaLabel` | `string` | No | — | ARIA label for accessibility |
| `className` | `string` | No | — | Additional CSS class |
```
--------------------------------
### Basic InputRangeField Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/inputrangefield.md
Demonstrates how to use the InputRangeField component with a label and placeholder. It includes event handlers for change, focus, and blur, and shows how to manage the input value state.
```javascript
import InputRangeField from 'react-date-range/dist/components/InputRangeField';
function MyComponent() {
const [value, setValue] = useState('7');
const handleChange = (numValue) => {
setValue(String(numValue));
// Generate range: today minus numValue days to today
const range = {
startDate: addDays(new Date(), -numValue + 1),
endDate: new Date(),
};
onRangeChange(range);
};
return (
console.log('Focused')}
onBlur={() => console.log('Blurred')}
/>
);
}
```
--------------------------------
### MonthDisplayRange Object
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Represents the full display range for a month, including any necessary padding from adjacent months. It provides start and end dates for the displayed calendar view, as well as the actual start and end dates of the month itself.
```APIDOC
## MonthDisplayRange Object
### Description
Represents the full display range for a month including week padding.
### Type Definition
```javascript
{
start: Date,
end: Date,
startDateOfMonth: Date,
endDateOfMonth: Date,
}
```
### Properties
| Property | Type | Description |
|----------|------|-------------|
| `start` | `Date` | First day displayed (may be from previous month) |
| `end` | `Date` | Last day displayed (may be in next month) |
| `startDateOfMonth` | `Date` | First day of the actual month |
| `endDateOfMonth` | `Date` | Last day of the actual month |
### Returned by
`getMonthDisplayRange(date, dateOptions, fixedHeight)`
```
--------------------------------
### MonthDisplayRange Object Type Definition
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Defines the structure of the MonthDisplayRange object, representing the full display range for a month, including week padding. It contains start and end dates for the display, as well as the actual start and end dates of the month.
```typescript
{
start: Date,
end: Date,
startDateOfMonth: Date,
endDateOfMonth: Date,
}
```
--------------------------------
### Create Custom Static Ranges
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Demonstrates how to create custom static ranges using the `createStaticRanges` utility. This is useful for defining predefined date ranges like 'Last 7 Days'.
```javascript
import { createStaticRanges } from 'react-date-range';
const customRanges = createStaticRanges([
{
label: 'Last 7 Days',
range: () => ({
startDate: addDays(new Date(), -6),
endDate: new Date(),
}),
},
]);
```
--------------------------------
### Core Components
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
These are the main components that users can directly integrate into their applications.
```APIDOC
## Calendar
### Description
Single date picker component with month/year navigation.
### Link
./api-reference/calendar.md
```
```APIDOC
## DateRange
### Description
Date range selection with multi-range support.
### Link
./api-reference/daterange.md
```
```APIDOC
## DateRangePicker
### Description
Full-featured date range picker with predefined ranges.
### Link
./api-reference/daterangepicker.md
```
```APIDOC
## DefinedRange
### Description
Sidebar with predefined ranges and input fields.
### Link
./api-reference/definedrange.md
```
--------------------------------
### getRangeOptionValue(option)
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/definedrange.md
Gets the current value to display for an input range option.
```APIDOC
## getRangeOptionValue(option)
### Description
Gets the current value to display for an input range option.
### Signature
```javascript
getRangeOptionValue(option: InputRange) => string
```
### Parameters
#### Path Parameters
- `option` (InputRange) - Required - Input range configuration.
### Returns
String representation of the current value (or empty string if not applicable).
```
--------------------------------
### Utilities and Types
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
This section covers utility functions, type definitions, and configuration options available for use.
```APIDOC
## Utility Functions
### Description
Helper functions for common tasks within the library.
### Functions
- `createStaticRanges`
- `calcFocusDate`
- `findNextRangeIndex`
### Link
./api-reference/utility-functions.md
```
```APIDOC
## Types
### Description
Type definitions for various data structures used in the library.
### Types
- `Range`
- `StaticRange`
- `InputRange`
- `Preview`
### Link
./types.md
```
```APIDOC
## Configuration
### Description
Details all configurable props and their default values.
### Link
./configuration.md
```
```APIDOC
## Errors
### Description
Information on error handling, validation, and warnings.
### Link
./errors.md
```
--------------------------------
### React Date Range Project Structure
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Overview of the directory structure for the react-date-range project, indicating the location of various documentation files.
```bash
/output
├── README.md (this file)
├── configuration.md - All props and defaults
├── types.md - Type definitions
├── errors.md - Error handling and validation
├── api-reference/
│ ├── calendar.md
│ ├── daterange.md
│ ├── daterangepicker.md
│ ├── definedrange.md
│ ├── month.md
│ ├── daycell.md
│ ├── dateinput.md
│ ├── inputrangefield.md
│ └── utility-functions.md
```
--------------------------------
### Basic DatePicker Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Demonstrates the basic usage of the DatePicker component. It takes a date prop and an onChange handler to capture selected dates.
```javascript
import { Calendar } from 'react-date-range';
class MyComponent extends Component {
handleSelect(date){
console.log(date); // native Date object
}
render(){
return (
)
}
}
```
--------------------------------
### Range Object Type
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/README.md
Defines the structure of a range object, including start and end dates, key, color, and display options.
```javascript
{
startDate?: Date,
endDate?: Date,
key?: string,
color?: string,
autoFocus?: boolean,
disabled?: boolean,
showDateDisplay?: boolean,
}
```
--------------------------------
### Handling Missing Props with Defaults
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/errors.md
Demonstrates how missing props like onChange, ranges, preview, or locale are handled by providing default values or conditional execution.
```javascript
// If onChange not provided
onChange && onChange(date); // Silently skips callback
// If ranges not provided
ranges || [] // Uses empty array
// If preview not provided
preview || this.state.preview // Uses internal state
// If locale not provided
locale: defaultLocale // Uses enUS from date-fns
```
--------------------------------
### Date Range Mode - In Range
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daycell.md
Days that fall between the start and end dates of a selected range are visually indicated when `displayMode` is 'dateRange'.
```plaintext
┌───┐
│ │
├───┤ ← Highlighted
│ │
└───┘
```
--------------------------------
### Basic Date Range Selection
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daterange.md
Demonstrates how to use the DateRange component for selecting a single date range. Includes necessary imports and state management for ranges and focus. Ensure default styles and themes are imported.
```javascript
import React, { useState } from 'react';
import { DateRange } from 'react-date-range';
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';
function DateRangeSelector() {
const [ranges, setRanges] = useState([
{
startDate: new Date(2024, 0, 1),
endDate: new Date(2024, 0, 31),
key: 'selection',
color: '#3d91ff',
},
]);
const [focusedRange, setFocusedRange] = useState([0, 0]);
const handleChange = (changes) => {
const newRanges = ranges.map((range, i) => {
if (changes[range.key || `range${i + 1}`]) {
return {
...range,
...changes[range.key || `range${i + 1}`],
};
}
return range;
});
setRanges(newRanges);
};
return (
);
}
export default DateRangeSelector;
```
--------------------------------
### defaultInputRanges
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/utility-functions.md
Predefined input ranges for relative date selections based on user input, including 'days up to today' and 'days starting today'.
```APIDOC
## defaultInputRanges
### Description
Predefined input ranges for relative date selections based on user input.
### Type
`Array`
### Included ranges:
1. **"days up to today"** - Selects a range ending today, starting N days ago
- Accepts numeric input for number of days
- Example: Input "7" gives last 7 days ending today
2. **"days starting today"** - Selects a range starting today, ending N days from now
- Accepts numeric input for number of days
- Example: Input "7" gives today plus next 6 days
### Example
```javascript
import { DateRangePicker, defaultInputRanges } from 'react-date-range';
```
```
--------------------------------
### date
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Sets the initial date value for the calendar.
```APIDOC
## date
### Description
Sets the initial date value for the calendar.
### Type
Date
```
--------------------------------
### Range Object Shape
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Defines the structure for a date range object, including start and end dates, color, key, and display/focus/disabled states.
```javascript
{
startDate: PropTypes.object,
endDate: PropTypes.object,
color: PropTypes.string,
key: PropTypes.string,
autoFocus: PropTypes.bool,
disabled: PropTypes.bool,
showDateDisplay: PropTypes.bool,
}
```
--------------------------------
### Localized Calendar (German)
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/configuration.md
Set up a calendar with German localization. Import the 'de' locale from 'date-fns/locale' and configure date and month display formats.
```javascript
import { de } from 'date-fns/locale';
```
--------------------------------
### Applying AriaLabels to Calendar Component
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Example of how to pass an AriaLabels object to the Calendar component to configure accessibility labels for input fields and navigation buttons.
```javascript
```
--------------------------------
### showPreview
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Controls the visibility of the preview range.
```APIDOC
## showPreview
### Description
Controls the visibility of the preview range.
### Type
Boolean
### Default
`true`
```
--------------------------------
### DateOptions Object Type
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Defines options for date-fns functions, controlling locale and week behavior. Use this to customize date formatting and week start day.
```javascript
{
locale: Locale,
weekStartsOn?: number,
}
```
--------------------------------
### preview
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Displays a preview range and overwrites the default preview of `DateRange`. Expected shape: `{ startDate: Date, endDate: Date, color: String }`.
```APIDOC
## preview
### Description
Displays a preview range and overwrites the default preview of `DateRange`. Expected shape: `{ startDate: Date, endDate: Date, color: String }`.
### Type
Object
```
--------------------------------
### moveRangeOnFirstSelection
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Controls whether the date range should move with the first date selection. If false, the end date will be replaced by the start date unless `retainEndDateOnFirstSelection` is true.
```APIDOC
## moveRangeOnFirstSelection
### Description
Controls whether the date range should move with the first date selection. If false, the end date will be replaced by the start date unless `retainEndDateOnFirstSelection` is true.
### Type
Boolean
### Default
`false`
```
--------------------------------
### Basic DateRangePicker Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/README.md
Shows how to use the DateRangePicker component for selecting date ranges. It requires an array of ranges and an onChange handler.
```javascript
import { DateRangePicker } from 'react-date-range';
class MyComponent extends Component {
handleSelect(ranges){
console.log(ranges);
// {
// selection: {
// startDate: [native Date Object],
// endDate: [native Date Object],
// }
// }
}
render(){
const selectionRange = {
startDate: new Date(),
endDate: new Date(),
key: 'selection',
}
return (
)
}
}
```
--------------------------------
### PropType Validation Errors in Development
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/errors.md
These examples show common PropType violations that will trigger console warnings during development. Ensure props are of the correct type and format.
```jsx
// ⚠ Warning: date should be object
```
```jsx
// ⚠ Warning: onChange is required
```
```jsx
// ⚠ Warning: should be Date objects
```
```jsx
// ⚠ Warning: should be 'vertical' or 'horizontal'
```
--------------------------------
### Use DefinedRange with Default Labels
Source: https://github.com/hypeserver/react-date-range/blob/master/src/components/DefinedRange/README.md
Demonstrates the basic usage of the DefinedRange component with its default static range labels. Requires importing useState and the DefinedRange component.
```jsx
import { useState } from 'react';
const [state, setState] = useState([
{
startDate: new Date(),
endDate: null,
key: 'selection'
}
]);
setState([item.selection])}
ranges={state}
/>;
```
--------------------------------
### Validating Date Range Props
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/errors.md
Checks if the provided start and end dates are valid and not in the wrong order before rendering the DateRange component. This prevents rendering with invalid state.
```javascript
const isValidDateRange = (startDate, endDate) => {
return startDate && endDate && !isAfter(startDate, endDate);
};
if (!isValidDateRange(range.startDate, range.endDate)) {
return Invalid date range
;
}
;
```
--------------------------------
### Basic DateRangePicker Usage
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daterangepicker.md
Demonstrates how to integrate the DateRangePicker component into a React application. It includes state management for selected ranges and basic configuration options.
```javascript
import React, { useState } from 'react';
import { DateRangePicker } from 'react-date-range';
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';
function MyDateRangePicker() {
const [ranges, setRanges] = useState([
{
startDate: new Date(),
endDate: new Date(),
key: 'selection',
},
]);
return (
{
setRanges([
{
...ranges[0],
...changes.selection,
},
]);
}}
months={2}
direction="horizontal"
showMonthAndYearPickers={true}
showPreview={true}
/>
);
}
export default MyDateRangePicker;
```
--------------------------------
### Custom Styling InputRangeField
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/inputrangefield.md
Example of how to apply custom CSS classes to the InputRangeField component for distinct styling. This allows overriding default styles for the container, input, and label.
```javascript
```
--------------------------------
### Full-Featured Date Range Picker
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/configuration.md
Configure a comprehensive date range picker with multiple months, custom date formats, and range colors. Ensure 'enUS' locale is imported if not default.
```javascript
{
// Handle changes
}}
months={2}
direction="horizontal"
minDate={new Date(2020, 0, 1)}
maxDate={new Date(2030, 11, 31)}
disabledDates={disabledDateArray}
dragSelectionEnabled={true}
editableDateInputs={true}
showMonthArrow={true}
showMonthAndYearPickers={true}
dateDisplayFormat="MMM d, yyyy"
monthDisplayFormat="MMM yyyy"
locale={enUS}
rangeColors={['#3d91ff', '#3ecf8e']}
/>
```
--------------------------------
### Multi-Range Selection
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daterange.md
Shows how to configure the DateRange component to handle multiple, distinct date ranges simultaneously. Each range is managed with a unique key.
```javascript
const [ranges, setRanges] = useState([
{
startDate: new Date(2024, 0, 1),
endDate: new Date(2024, 0, 10),
key: 'selection1',
},
{
startDate: new Date(2024, 0, 20),
endDate: new Date(2024, 0, 25),
key: 'selection2',
},
]);
const handleChange = (changes) => {
const newRanges = ranges.map(range => ({
...range,
...(changes[range.key] && changes[range.key]),
}));
setRanges(newRanges);
};
;
```
--------------------------------
### FocusedRange
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
A tuple indicating which range and step is currently focused. It helps manage the user's interaction with date ranges, specifying which date (start or end) of which range is currently active.
```APIDOC
## FocusedRange
A tuple indicating which range and step is currently focused.
### Type Definition
```javascript
[number, number]
```
### Structure
- `[0]` (number): Index of the focused range in the `ranges` array
- `[1]` (number): Step index within the range: 0 for startDate, 1 for endDate
### Usage
```javascript
const [focusedRange, setFocusedRange] = useState([0, 0]);
// User can now edit the start date of the first range
// Advance to the end date
setFocusedRange([0, 1]);
// Move to the second range
setFocusedRange([1, 0]);
```
```
--------------------------------
### Using Default Static Ranges in DateRangePicker
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/utility-functions.md
Integrate `defaultStaticRanges` to provide users with a set of commonly used predefined date ranges for quick selection. Ensure `DateRangePicker` and `defaultStaticRanges` are imported.
```javascript
import { DateRangePicker, defaultStaticRanges } from 'react-date-range';
```
--------------------------------
### rangeShape PropType Definition
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daycell.md
The `rangeShape` PropType is exported for use in defining the shape of range objects in other components. It specifies properties like start and end dates, color, and other configuration options.
```javascript
export const rangeShape = PropTypes.shape({
startDate: PropTypes.object,
endDate: PropTypes.object,
color: PropTypes.string,
key: PropTypes.string,
autoFocus: PropTypes.bool,
disabled: PropTypes.bool,
showDateDisplay: PropTypes.bool,
});
```
--------------------------------
### Import Styles and Theme for react-date-range
Source: https://github.com/hypeserver/react-date-range/blob/master/demo/README.md
Import the main CSS file and the default theme CSS file. These are required for the date range picker to display correctly.
```javascript
import 'react-date-range/dist/styles.css'; // main css file
import 'react-date-range/dist/theme/default.css'; // theme css file
```
--------------------------------
### Import DayCell and rangeShape
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/api-reference/daycell.md
Import the DayCell component and the rangeShape type for defining date ranges.
```javascript
import DayCell, { rangeShape } from 'react-date-range/dist/components/DayCell';
```
--------------------------------
### Adjust Range for Disabled Dates
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/errors.md
When a selected date range includes disabled dates, the range automatically adjusts to exclude them. The adjustment logic depends on whether the start or end date is being edited.
```javascript
const inValidDatesWithinRange = disabledDates.filter(disabledDate =>
isWithinInterval(disabledDate, {
start: startDate,
end: endDate,
})
);
if (inValidDatesWithinRange.length > 0) {
if (isStartDateSelected) {
startDate = addDays(max(inValidDatesWithinRange), 1);
} else {
endDate = addDays(min(inValidDatesWithinRange), -1);
}
}
```
```javascript
// User selects: Jan 10 - Jan 20
// → System detects Jan 15 is disabled
// → Range adjusts based on which end is being edited:
// - If editing start: becomes Jan 16 - Jan 20
// - If editing end: becomes Jan 10 - Jan 14
```
--------------------------------
### Customizing Calendar Class Names
Source: https://github.com/hypeserver/react-date-range/blob/master/_autodocs/types.md
Example of how to use the classNames prop to apply custom CSS classes to specific elements within the Calendar component. This allows for detailed styling of the date picker interface.
```jsx
```
--------------------------------
### 2 Month View
Source: https://github.com/hypeserver/react-date-range/blob/master/src/components/DateRangePicker/README.md
Displays two months side-by-side. Configure the number of months using the 'months' prop.
```jsx
import { addDays } from 'date-fns';
import { useState } from 'react';
const [state, setState] = useState([
{
startDate: new Date(),
endDate: addDays(new Date(), 7),
key: 'selection'
}
]);
setState([item.selection])}
showSelectionPreview={true}
moveRangeOnFirstSelection={false}
months={2}
ranges={state}
direction="horizontal"
/>;
```