react-dates

An easily internationalizable, mobile-friendly datepicker library for the w...

README

# react-dates [![Version Badge][npm-version-svg]][package-url]
[![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]

An easily internationalizable, accessible, mobile-friendly datepicker library for the web.


react-dates in action

Live Playground


For examples of the datepicker in action, go to react-dates.github.io.

OR

To run that demo on your own computer:
Clone this repository
npm install
npm run storybook
Visit http://localhost:6006/

Getting Started

Install dependencies

Ensure packages are installed with correct version numbers by running (from your command line):
  1. ```sh
  2.   (
  3.     export PKG=react-dates;
  4.     npm info "$PKG" peerDependencies --json | command sed 's/[\{\},]//g ; s/: /@/g; s/ *//g' | xargs npm install --save "$PKG"
  5.   )
  6. ```

  Which produces and runs a command like:

  1. ```sh
  2.   npm install --save react-dates moment@>=#.## react@>=#.## react-dom@>=#.##
  3. ```

  > If you are running Windows, that command will not work, but if you are running npm 5 or higher, you can run npx install-peerdeps react-dates on any platform

Initialize

  1. ``` js
  2. import 'react-dates/initialize';
  3. ```

As of v13.0.0 of react-dates, this project relies on react-with-styles. If you want to continue using CSS stylesheets and classes, there is a little bit of extra set-up required to get things going. As such, you need to import react-dates/initialize to set up class names on our components. This import should go at the top of your application as you won't be able to import any react-dates components without it.

Note: This component assumes box-sizing: border-box is set globally in your page's CSS.

Include component

  1. ``` js
  2. import { DateRangePicker, SingleDatePicker, DayPickerRangeController } from 'react-dates';
  3. ```

Webpack

Using Webpack with CSS loader, add the following import to your app:
  1. ``` js
  2. import 'react-dates/lib/css/_datepicker.css';
  3. ```

Without Webpack:

Create a CSS file with the contents of `require.resolve('react-dates/lib/css/_datepicker.css')` and include it in your html `` section.

To see this in action, you can check out https://github.com/majapw/react-dates-demo which adds react-dates on top of a simple create-react-app setup.

Overriding Base Class

By default react-dates will use PureComponent conditionally if it is available.  However, it is possible to override this setting and use Component and shouldComponentUpdate instead. It is also possible to override the logic in build/util/baseClass if you know that you are using a React version with PureComponent.
  1. ``` js
  2.     import React from 'react';
  3.     export default React.PureComponent;
  4.     export const pureComponentAvailable = true;
  5. ```

Overriding styles

Right now, the easiest way to tweak react-dates to your heart's content is to create another stylesheet to override the default react-dates styles. For example, you could create a file named react_dates_overrides.css with the following contents (Make sure when you import said file to your app.js, you import it after the react-dates styles):

  1. ```css
  2. // NOTE: the order of these styles DO matter

  3. // Will edit everything selected including everything between a range of dates
  4. .CalendarDay__selected_span {
  5.   background: #82e0aa; //background
  6.   color: white; //text
  7.   border: 1px solid $light-red; //default styles include a border
  8. }

  9. // Will edit selected date or the endpoints of a range of dates
  10. .CalendarDay__selected {
  11.   background: $dark-red;
  12.   color: white;
  13. }

  14. // Will edit when hovered over. _span style also has this property
  15. .CalendarDay__selected:hover {
  16.   background: orange;
  17.   color: white;
  18. }

  19. // Will edit when the second date (end date) in a range of dates
  20. // is not yet selected. Edits the dates between your mouse and said date
  21. .CalendarDay__hovered_span:hover,
  22. .CalendarDay__hovered_span {
  23.   background: brown;
  24. }
  25. ```

This would override the background and text colors applied to highlighted calendar days. You can use this method with the default set-up to override any aspect of the calendar to have it better fit to your particular needs. If there are any styles that you need that aren't listed here, you can always check the source css of each element.

Make some awesome datepickers


We provide a handful of components for your use. If you supply essential props to each component, you'll get a full featured interactive date picker. With additional optional props, you can customize the look and feel of the inputs, calendar, etc. You can see what each of the props do in the live demo or explore
how to properly wrap the pickers in the examples folder.

DateRangePicker

The DateRangePicker is a fully controlled component that allows users to select a date range. You can control the selected
dates using the startDate, endDate, and onDatesChange props as shown below. The DateRangePicker also manages internal
state for partial dates entered by typing (although onDatesChange will not trigger until a date has been entered
completely in that case). Similarly, you can control which input is focused as well as calendar visibility (the calendar is
only visible if focusedInput is defined) with the focusedInput and onFocusChange props as shown below.

Here is the minimum REQUIRED setup you need to get the DateRangePicker working:
  1. ``` js
  2. <DateRangePicker
  3.   startDate={this.state.startDate} // momentPropTypes.momentObj or null,
  4.   startDateId="your_unique_start_date_id" // PropTypes.string.isRequired,
  5.   endDate={this.state.endDate} // momentPropTypes.momentObj or null,
  6.   endDateId="your_unique_end_date_id" // PropTypes.string.isRequired,
  7.   onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired,
  8.   focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
  9.   onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
  10. />
  11. ```

The following is a list of other OPTIONAL props you may provide to the DateRangePicker to customize appearance and behavior to your heart's desire. All constants (indicated by ALL_CAPS) are provided as named exports in react-dates/constants. Please explore the storybook for more information on what each of these props do.
  1. ``` js
  2. // input related props
  3. startDatePlaceholderText: PropTypes.string,
  4. endDatePlaceholderText: PropTypes.string,
  5. startDateAriaLabel: PropTypes.string,
  6. endDateAriaLabel: PropTypes.string,
  7. startDateTitleText: PropTypes.string,
  8. endDateTitleText: PropTypes.string,
  9. disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf([START_DATE, END_DATE])]),
  10. required: PropTypes.bool,
  11. readOnly: PropTypes.bool,
  12. screenReaderInputMessage: PropTypes.string,
  13. showClearDates: PropTypes.bool,
  14. showDefaultInputIcon: PropTypes.bool,
  15. customInputIcon: PropTypes.node,
  16. customArrowIcon: PropTypes.node,
  17. customCloseIcon: PropTypes.node,
  18. inputIconPosition: PropTypes.oneOf([ICON_BEFORE_POSITION, ICON_AFTER_POSITION]),
  19. noBorder: PropTypes.bool,
  20. block: PropTypes.bool,
  21. small: PropTypes.bool,
  22. regular: PropTypes.bool,
  23. autoComplete: PropTypes.string,

  24. // calendar presentation and interaction related props
  25. renderMonthText: mutuallyExclusiveProps(PropTypes.func, 'renderMonthText', 'renderMonthElement'), // (month) => PropTypes.string,
  26. orientation: PropTypes.oneOf([HORIZONTAL_ORIENTATION, VERTICAL_ORIENTATION]),
  27. anchorDirection: PropTypes.oneOf([ANCHOR_LEFT, ANCHOR_RIGHT]),
  28. openDirection: PropTypes.oneOf([OPEN_DOWN, OPEN_UP]),
  29. horizontalMargin: PropTypes.number,
  30. withPortal: PropTypes.bool,
  31. withFullScreenPortal: PropTypes.bool,
  32. appendToBody: PropTypes.bool,
  33. disableScroll: PropTypes.bool,
  34. daySize: nonNegativeInteger,
  35. isRTL: PropTypes.bool,
  36. initialVisibleMonth: PropTypes.func,
  37. firstDayOfWeek: PropTypes.oneOf([0, 1, 2, 3, 4, 5, 6]),
  38. numberOfMonths: PropTypes.number,
  39. keepOpenOnDateSelect: PropTypes.bool,
  40. reopenPickerOnClearDates: PropTypes.bool,
  41. renderCalendarInfo: PropTypes.func,
  42. renderMonthElement: mutuallyExclusiveProps(PropTypes.func, 'renderMonthText', 'renderMonthElement'), PropTypes.func, // ({ month, onMonthSelect, onYearSelect, isVisible }) => PropTypes.node,
  43. hideKeyboardShortcutsPanel: PropTypes.bool,
  44. verticalSpacing: PropTypes.number,

  45. // navigation related props
  46. navPrev: PropTypes.node,
  47. navNext: PropTypes.node,
  48. onPrevMonthClick: PropTypes.func,
  49. onNextMonthClick: PropTypes.func,
  50. onClose: PropTypes.func,
  51. transitionDuration: nonNegativeInteger, // milliseconds

  52. // day presentation and interaction related props
  53. renderCalendarDay: PropTypes.func,
  54. renderDayContents: PropTypes.func,
  55. minimumNights: PropTypes.number,
  56. minDate: momentPropTypes.momentObj,
  57. maxDate: momentPropTypes.momentObj,
  58. enableOutsideDays: PropTypes.bool,
  59. isDayBlocked: PropTypes.func,
  60. isOutsideRange: PropTypes.func,
  61. isDayHighlighted: PropTypes.func,

  62. // internationalization props
  63. displayFormat: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  64. monthFormat: PropTypes.string,
  65. weekDayFormat: PropTypes.string,
  66. phrases: PropTypes.shape(getPhrasePropTypes(DateRangePickerPhrases)),
  67. dayAriaLabelFormat: PropTypes.string,
  68. ```

SingleDatePicker

The SingleDatePicker is a fully controlled component that allows users to select a single date. You can control the selected
date using the date and onDateChange props as shown below. The SingleDatePicker also manages internal
state for partial dates entered by typing (although onDateChange will not trigger until a date has been entered
completely in that case). Similarly, you can control whether or not the input is focused (calendar visibility is also
controlled with the same props) with the focused and onFocusChange props as shown below.

Here is the minimum REQUIRED setup you need to get the SingleDatePicker working:
  1. ``` js
  2. <SingleDatePicker
  3.   date={this.state.date} // momentPropTypes.momentObj or null
  4.   onDateChange={date => this.setState({ date })} // PropTypes.func.isRequired
  5.   focused={this.state.focused} // PropTypes.bool
  6.   onFocusChange={({ focused }) => this.setState({ focused })} // PropTypes.func.isRequired
  7.   id="your_unique_id" // PropTypes.string.isRequired,
  8. />
  9. ```

The following is a list of other OPTIONAL props you may provide to the SingleDatePicker to customize appearance and behavior to your heart's desire. All constants (indicated by ALL_CAPS) are provided as named exports in react-dates/constants. Please explore the storybook for more information on what each of these props do.
  1. ``` js
  2. // input related props
  3. placeholder: PropTypes.string,
  4. ariaLabel: PropTypes.string,
  5. titleText: PropTypes.string,
  6. disabled: PropTypes.bool,
  7. required: PropTypes.bool,
  8. readOnly: PropTypes.bool,
  9. screenReaderInputMessage: PropTypes.string,
  10. showClearDate: PropTypes.bool,
  11. customCloseIcon: PropTypes.node,
  12. showDefaultInputIcon: PropTypes.bool,
  13. customInputIcon: PropTypes.node,
  14. inputIconPosition: PropTypes.oneOf([ICON_BEFORE_POSITION, ICON_AFTER_POSITION]),
  15. noBorder: PropTypes.bool,
  16. block: PropTypes.bool,
  17. small: PropTypes.bool,
  18. regular: PropTypes.bool,
  19. autoComplete: PropTypes.string,

  20. // calendar presentation and interaction related props
  21. renderMonthText: mutuallyExclusiveProps(PropTypes.func, 'renderMonthText', 'renderMonthElement'), // (month) => PropTypes.string,
  22. orientation: PropTypes.oneOf([HORIZONTAL_ORIENTATION, VERTICAL_ORIENTATION]),
  23. anchorDirection: PropTypes.oneOf([ANCHOR_LEFT, ANCHOR_RIGHT]),
  24. openDirection: PropTypes.oneOf([OPEN_DOWN, OPEN_UP]),
  25. horizontalMargin: PropTypes.number,
  26. withPortal: PropTypes.bool,
  27. withFullScreenPortal: PropTypes.bool,
  28. appendToBody: PropTypes.bool,
  29. disableScroll: PropTypes.bool,
  30. initialVisibleMonth: PropTypes.func,
  31. firstDayOfWeek: PropTypes.oneOf([0, 1, 2, 3, 4, 5, 6]),
  32. numberOfMonths: PropTypes.number,
  33. keepOpenOnDateSelect: PropTypes.bool,
  34. reopenPickerOnClearDate: PropTypes.bool,
  35. renderCalendarInfo: PropTypes.func,
  36. renderMonthElement: mutuallyExclusiveProps(PropTypes.func, 'renderMonthText', 'renderMonthElement'), // ({ month, onMonthSelect, onYearSelect, isVisible }) => PropTypes.node,
  37. hideKeyboardShortcutsPanel: PropTypes.bool,
  38. daySize: nonNegativeInteger,
  39. isRTL: PropTypes.bool,
  40. verticalSpacing: PropTypes.number,

  41. // navigation related props
  42. navPrev: PropTypes.node,
  43. navNext: PropTypes.node,
  44. onPrevMonthClick: PropTypes.func,
  45. onNextMonthClick: PropTypes.func,
  46. onClose: PropTypes.func,
  47. transitionDuration: nonNegativeInteger, // milliseconds

  48. // day presentation and interaction related props
  49. renderCalendarDay: PropTypes.func,
  50. renderDayContents: PropTypes.func,
  51. enableOutsideDays: PropTypes.bool,
  52. isDayBlocked: PropTypes.func,
  53. isOutsideRange: PropTypes.func,
  54. isDayHighlighted: PropTypes.func,

  55. // internationalization props
  56. displayFormat: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  57. monthFormat: PropTypes.string,
  58. weekDayFormat: PropTypes.string,
  59. phrases: PropTypes.shape(getPhrasePropTypes(SingleDatePickerPhrases)),
  60. dayAriaLabelFormat: PropTypes.string,
  61. ```

DayPickerRangeController

The DayPickerRangeController is a calendar-only version of the DateRangePicker. There are no inputs (which also means
that currently, it is not keyboard accessible) and the calendar is always visible, but you can select a date range much in the same way you would with the DateRangePicker. You can control the selected
dates using the startDate, endDate, and onDatesChange props as shown below. Similarly, you can control which input is focused with the focusedInput and onFocusChange props as shown below. The user will only be able to select a date if focusedInput is provided.

Here is the minimum REQUIRED setup you need to get the DayPickerRangeController working:
  1. ``` js
  2. <DayPickerRangeController
  3.   startDate={this.state.startDate} // momentPropTypes.momentObj or null,
  4.   endDate={this.state.endDate} // momentPropTypes.momentObj or null,
  5.   onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired,
  6.   focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
  7.   onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
  8.   initialVisibleMonth={() => moment().add(2, "M")} // PropTypes.func or null,
  9. />
  10. ```

The following is a list of other OPTIONAL props you may provide to the DayPickerRangeController to customize appearance and behavior to your heart's desire. Again, please explore the storybook for more information on what each of these props do.
  1. ``` js
  2.   // calendar presentation and interaction related props
  3.   enableOutsideDays: PropTypes.bool,
  4.   numberOfMonths: PropTypes.number,
  5.   orientation: ScrollableOrientationShape,
  6.   withPortal: PropTypes.bool,
  7.   initialVisibleMonth: PropTypes.func,
  8.   renderCalendarInfo: PropTypes.func,
  9.   renderMonthElement: mutuallyExclusiveProps(PropTypes.func, 'renderMonthText', 'renderMonthElement'), // ({ month, onMonthSelect, onYearSelect, isVisible }) => PropTypes.node,
  10.   onOutsideClick: PropTypes.func,
  11.   keepOpenOnDateSelect: PropTypes.bool,
  12.   noBorder: PropTypes.bool,

  13.   // navigation related props
  14.   navPrev: PropTypes.node,
  15.   navNext: PropTypes.node,
  16.   onPrevMonthClick: PropTypes.func,
  17.   onNextMonthClick: PropTypes.func,
  18.   transitionDuration: nonNegativeInteger, // milliseconds

  19.   // day presentation and interaction related props
  20.   renderCalendarDay: PropTypes.func,
  21.   renderDayContents: PropTypes.func,
  22.   minimumNights: PropTypes.number,
  23.   isOutsideRange: PropTypes.func,
  24.   isDayBlocked: PropTypes.func,
  25.   isDayHighlighted: PropTypes.func,

  26.   // internationalization props
  27.   monthFormat: PropTypes.string,
  28.   weekDayFormat: PropTypes.string,
  29.   phrases: PropTypes.shape(getPhrasePropTypes(DayPickerPhrases)),
  30.   dayAriaLabelFormat: PropTypes.string,
  31. />
  32. ```

Localization


Moment.js is a peer dependency ofreact-dates. The latter then uses a single instance of moment which is imported in one’s project. Loading a locale is done by calling moment.locale(..) in the component where moment is imported, with the locale key of choice. For instance:

  1. ``` js
  2. moment.locale('pl'); // Polish
  3. ```

However, this only solves date localization. For complete internationalization of the components, react-dates defines a certain amount of user interface strings in English which can be changed through thephrases prop (explore the storybook for examples). For accessibility and usability concerns,all these UI elements should be translated.

Advanced


react-dates no longer relies strictly on CSS, but rather relies on react-with-styles as an abstraction layer between how styles are applied and how they are written. The instructions above will get the project working out of the box, but there's a lot more customization that can be done.

Interfaces


The react-dates/initialize script actually relies on react-with-styles-interface-css under the hood. If you are interested in a different solution for styling in your project, you can do your own initialization of a another interface. At Airbnb, for instance, we rely on Aphrodite under the hood and therefore use the Aphrodite interface forreact-with-styles. If you want to do the same, you would use the following pattern:
  1. ``` js
  2. import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet';
  3. import aphroditeInterface from 'react-with-styles-interface-aphrodite';
  4. import DefaultTheme from 'react-dates/lib/theme/DefaultTheme';

  5. ThemedStyleSheet.registerInterface(aphroditeInterface);
  6. ThemedStyleSheet.registerTheme(DefaultTheme);
  7. ```

The above code has to be run before any react-dates component is imported. Otherwise, you will get an error. Also note that if you register any custom interface manually, you must also manually register a theme.

Theming

react-dates also now supports a different way to theme. You can see the default theme values in this file and you would override them in the following manner:
  1. ``` js
  2. import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet';
  3. import aphroditeInterface from 'react-with-styles-interface-aphrodite';
  4. import DefaultTheme from 'react-dates/lib/theme/DefaultTheme';

  5. ThemedStyleSheet.registerInterface(aphroditeInterface);
  6. ThemedStyleSheet.registerTheme({
  7.   reactDates: {
  8.     ...DefaultTheme.reactDates,
  9.     color: {
  10.       ...DefaultTheme.reactDates.color,
  11.       highlighted: {
  12.         backgroundColor: '#82E0AA',
  13.         backgroundColor_active: '#58D68D',
  14.         backgroundColor_hover: '#58D68D',
  15.         color: '#186A3B',
  16.         color_active: '#186A3B',
  17.         color_hover: '#186A3B',
  18.       },
  19.     },
  20.   },
  21. });
  22. ```

The above code would use shades of green instead of shades of yellow for the highlight color on CalendarDay components. Note that you must register an interface if you manually register a theme. One will not work without the other.

A note on using react-with-styles-interface-css

The default interface that react-dates ships with is the CSS interface. If you want to use this interface along with the theme registration method, you will need to rebuild the core_datepicker.css file. We do not currently expose a utility method to build this file, but you can follow along with the code in https://github.com/react-dates/react-dates/blob/HEAD/scripts/buildCSS.js to build your own custom themed CSS file.

[package-url]: https://npmjs.org/package/react-dates
[npm-version-svg]: http://versionbadg.es/react-dates/react-dates.svg
[travis-svg]: https://travis-ci.org/react-dates/react-dates.svg
[travis-url]: https://travis-ci.org/react-dates/react-dates
[deps-svg]: https://david-dm.org/react-dates/react-dates.svg
[deps-url]: https://david-dm.org/react-dates/react-dates
[dev-deps-svg]: https://david-dm.org/react-dates/react-dates/dev-status.svg
[dev-deps-url]: https://david-dm.org/react-dates/react-dates#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/react-dates.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/react-dates.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/react-dates.svg
[downloads-url]: http://npm-stat.com/charts.html?package=react-dates