react-date-range Documentation

repository·master·Indexed 25 days ago

https://github.com/hypeserver/react-date-range

A React component library for selecting single dates or date ranges, built on top of date-fns and using native JavaScript Date objects. It provides four standalone components: DateRange, DateRangePicker, Calendar, and DefinedRange. Features include internationalization support for numerous locales, infinite scrolled mode, custom day cell rendering via dayContentRenderer, and accessibility configuration through ariaLabels.

Tokens
6.4K
Snippets
15
Records
39
Agent score
81%

What's inside react-date-range

  1. Install react-date-range and peer dependencies

    master

    Install the main package via npm. Note that react-date-range requires react and date-fns as peer dependencies, so you must ensure they are installed in your project.

    npm install --save react-date-range
    
    npm install --save react date-fns
  2. Import react-date-range styles and themes

    master

    Before using the components, you must import the main CSS file and a theme CSS file to ensure the date range components are styled correctly.

    import 'react-date-range/dist/styles.css'; // main css file
    import 'react-date-range/dist/theme/default.css'; // theme css file
  3. Configure Infinite Scrolled Mode

    master

    To enable infinite scrolling, set the scroll prop to { enabled: true }. This feature is influenced by the direction and months props. You can also customize the dimensions of the calendar and months within the scroll object.

    // shape of scroll prop
    scroll: {
      enabled: PropTypes.bool,
      monthHeight: PropTypes.number,
      longMonthHeight: PropTypes.number, // some months has 1 more row than others
      monthWidth: PropTypes.number, // just used when direction="horizontal"
      calendarWidth: PropTypes.number, // defaults monthWidth * months
      calendarHeight: PropTypes.number, // defaults monthHeight * months
    }),
  4. Use the DateRangePicker component

    master

    The DateRangePicker component wraps DefinedRange and Calendar components together. It allows for selecting date ranges and supports multiple ranges, custom day content, and accessibility labels. It extends all props from its underlying components.

    import { addDays } from 'date-fns';
    import { useState } from 'react';
    import { DateRangePicker } from 'react-date-range'; // Assuming standard import
    
    const [state, setState] = useState([
      {
        startDate: new Date(),
        endDate: addDays(new Date(), 7),
        key: 'selection'
      }
    ]);
    
    <DateRangePicker
      onChange={item => setState([item.selection])}
      showSelectionPreview={true}
      moveRangeOnFirstSelection={false}
      months={2}
      ranges={state}
      direction="horizontal"
    />;
  5. Import required styles for react-date-range

    master

    To ensure the calendar renders correctly, you must import the main skeleton styles and the default theme CSS files.

    import 'react-date-range/dist/styles.css'; // main style file
    import 'react-date-range/dist/theme/default.css'; // theme css file
  6. Configure DateRangePicker for multiple ranges

    master

    To support multiple independent date ranges, pass an array of range objects to the ranges prop. Each object in the array should include a unique key to identify the range in the onChange callback.

    import { addDays } from 'date-fns';
    import { useState } from 'react';
    
    const [state, setState] = useState({
      selection1: {
        startDate: addDays(new Date(), 1),
        endDate: null,
        key: 'selection1'
      },
      selection2: {
        startDate: addDays(new Date(), 4),
        endDate: addDays(new Date(), 8),
        key: 'selection2'
      },
      selection3: {
        startDate: addDays(new Date(), 8),
        endDate: addDays(new Date(), 10),
        key: 'selection3',
        autoFocus: false
      }
    });
    
    <DateRangePicker
      onChange={item => setState({ ...state, ...item })}
      ranges={[state.selection1, state.selection2, state.selection3]}
    />;
  7. Customize range labels in DefinedRange

    master

    You can customize the labels for static ranges in the DefinedRange component using the renderStaticRangeLabel prop and the staticRanges configuration.

    To use custom rendering:

    1. Define a function for renderStaticRangeLabel that returns your custom component.
    2. Provide a staticRanges array where each object contains:
      • label: The text label.
      • hasCustomRendering: A boolean set to true to indicate custom rendering is used.
      • range: A function that returns the date range object.
      • isSelected(): A function that returns a boolean indicating if the range is currently selected.
    import { useState } from 'react';
    
    const renderStaticRangeLabel = () => (
      <CustomStaticRangeLabelContent text={'This is a custom label content: '} />
    );
    
    class CustomStaticRangeLabelContent extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          currentDateString: Date(),
        };
    
        this.intervalId = setInterval(() => {
          this.setState({
            currentDateString: Date(),
          });
        }, 1000);
      }
    
      componentWillUnmount() {
        if (this.intervalId) {
          clearInterval(this.intervalId);
        }
      }
    
      render() {
        const { currentDateString } = this.state;
        const { text } = this.props;
    
        return (
          <span >
            <i>{text}</i>
            <span className={'random-date-string'}>
              <b>{currentDateString}</b>
            </span>
          </span>
        );
      }
    }
    
    const [state, setState] = useState([
      {
        startDate: new Date(),
        endDate: null,
        key: 'selection'
      }
    ]);
    
    <DefinedRange
      onChange={item => setState([item.selection])}
      ranges={state}
      renderStaticRangeLabel={renderStaticRangeLabel}
      staticRanges={[
        {
          label: 'Hoy',
          hasCustomRendering: true,
          range: () => ({
            startDate: new Date(),
            endDate: new Date()
          }),
          isSelected() {
            return true;
          }
        }
      ]}
    />;
  8. Use the DefinedRange component with default labels

    master

    The DefinedRange component can be used with its default range labels by providing a ranges prop containing an array of range objects and an onChange callback to update the state. A range object typically includes startDate, endDate, and a key.

    import { useState } from 'react';
    
    const [state, setState] = useState([
      {
        startDate: new Date(),
        endDate: null,
        key: 'selection'
      }
    ]);
    
    <DefinedRange
      onChange={item => setState([item.selection])}
      ranges={state}
    />;
  9. Implement Internationalization in Calendar

    master

    To localize the Calendar component, import the available locales from react-date-range/dist/locale and pass the desired locale object to the locale prop.

    Available locale keys include ar, bg, ca, cs, cy, da, de, el, enGB, enUS, eo, es, et, faIR, fi, fil, fr, hi, hr, hu, hy, id, is, it, ja, ka, ko, lt, lv, mk, nb, nl, pl, pt, ro, ru, sk, sl, sr, sv, th, tr, uk, vi, zhCN, and zhTW.

    import * as locales from 'react-date-range/dist/locale';
    import {useState} from 'react'
    
    // ... (locale mapping logic)
    
    const [locale, setLocale] = React.useState('ja');
    const [date, setDate] = useState(null);
    
    <div style={{ display: 'flex', flexFlow: 'column nowrap' }}>
      <select
        style={{ margin: '20px auto' }}
        onChange={e => setLocale(e.target.value)}
        value={locale}
      >
        {localeOptions.map((option, i) => (
          <option value={option.value} key={i}>
            {option.label}
          </option>
        ))}
      </select>
      <Calendar onChange={item => setDate(item)} locale={locales[locale]} date={date} />
    </div>
  10. Implement editable date inputs in DateRange

    master

    You can enable manual date entry by setting the editableDateInputs prop to true. This allows users to type dates directly into the input fields. Use the onChange callback to update your state with the new selection.

    import {useState} from 'react'
    const [state, setState] = useState([
        {
          startDate: new Date(),
          endDate: null,
          key: 'selection'
        }
      ]);
      
    <DateRange
      editableDateInputs={true}
      onChange={item => setState([item.selection])}
      moveRangeOnFirstSelection={false}
      ranges={state}
    />