1.0.0 • Published 11 months ago

@element-public/react-datepicker v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
11 months ago

Datepicker

Description

Datepicker provides a way for users to select a specific date or range of dates from a dialog or dropdown.

See live demos on storybook

Storybook Datepicker Demos

Install bundle from npm-e

npm i @element-public/react-components @element-public/themes

Optional: install the component individually

npm i @element-public/react-datepicker @element-public/themes

Open ~/.npmrc in an editor and add the following line to enable the @element-public scope:

@element-public:registry=https://npm.platforms.engineering

Troubleshooting

See below if you have never installed a package from Bayer's npm-enterprise or run into the following error:

npm ERR! code E401
npm ERR! Unable to authenticate, your authentication token seems to be invalid.
npm ERR! To correct this please trying logging in again with:
npm ERR!     npm login

Setup an access token

See the devtools npm-e guide to learn how to create an access token if this is the first time you are using a npm-e package at Bayer or you do not have a line that starts with the following in your ~/.npmrc file:

//npm.platforms.engineering/:_authToken=

Keyboard Navigation

Date Input

  • esc - Closes calendar
  • ArrowDown - Opens the calender when input is focused
  • Enter - If focused on the clearable icon it will clear the date picker value, if in the input it will submit the form.

Calendar

  • While focused on a day arrow keys allow for navigation around the calender.
  • Enter` - Selects the focused day

Highlighted Dates

Dates can be highlighted in a number of ways. The highlighted dates schema includes the following fields:

fielddescriptionexample(s)
includeDisabledBoolean that when set to true will highlight dates, even if they have been disabled.Enable highlighting of disabled days: { includeDisabled: true }
datesArray of valid date objects, most useful for scattered highlighted dates.Highlight today and a week from today (using date-dns add()): { dates: [new Date(), add(new Date(), {days: 7} ]}.
daysArray of days of the week as integers from 0 to 6. This will highlight every day of the week specified for the visible date.Highlight every Wednesday: { days: [3] }
daysOfMonthArray of days of the month as integers from 0 to 29-31. This will highlight every day of the month specified for the visible date.Highlight the 1st and 15th of the month: { daysOfMonth: [1, 15] }
from and toDate objects that represent the start and end date of a range, most useful for a contiguous block of highlighted dates. If only one is supplied (either from or to) the other will be considered infinity.Highlight every day before and including today: {to: new Date()} Highlight everything after (and including) today: {from: new Date()}
rangesArray of objects that allows multiple to/from ranges to be specified with the same rules. This also allows a configuration where you can specify everything up to a date and also everything after a date, leaving a range of highlighted dates in between.Only today is valid (using date-fns add()): { ranges: [ {to: add(new Date(), {days: -1})}, {from: add(new Date(), {days: 1} ]}
customPredictorCustom function that will be called during evaluation.Highlight even days: { customPredictor: date => date.getDate() % 2 === 0 }

Please note: All dates are inclusive and date comparisons ignore time.

Disabled Dates

Disabled dates share a similar schema as highlighted dates. The disabled dates schema includes the following fields:

fielddescriptionexample(s)
datesArray of valid date objects, most useful for scattered disabled dates.Disable today and a week from today (using date-dns add()): { dates: [new Date(), add(new Date(), {days: 7} ]}.
daysArray of days of the week as integers from 0 to 6. This will disable every day of the week specified for the visible date.Disable every Wednesday: { days: [3] }
daysOfMonthArray of days of the month as integers from 0 to 29-31. This will disable every day of the month specified for the visible date.Disable the 1st and 15th of the month: { daysOfMonth: [1, 15] }
from and toDate objects that represent the start and end date of a range, most useful for a contiguous block of disabled dates. If only one is supplied (either from or to) the other will be considered infinity.Disable every day before and including today: {to: new Date()} Disable everything after (and including) today: {from: new Date()}
rangesArray of objects that allows multiple to/from ranges to be specified with the same rules. This also allows a configuration where you can specify everything up to a date and also everything after a date, leaving a range of disabled dates in between.Only today is valid (using date-fns add()): { ranges: [ {to: add(new Date(), {days: -1})}, {from: add(new Date(), {days: 1} ]}
customPredictorCustom function that will be called during evaluation.Disable even days: { customPredictor: date => date.getDate() % 2 === 0 }

Please note: All dates are inclusive and date comparisons ignore time.

Calendar

The Calendar component may now be used separately for light-weight needs. Its features are limited and it is not intended as a full service calendar component at this time.

Date Formatting

Datepicker now uses date-fns for date formatting and supports the following tokens.

UnitPatternResult examplesNotes
EraG..GGGAD, BC
GGGGAnno Domini, Before Christ2
GGGGGA, B
Calendar yeary44, 1, 1900, 20175
yo44th, 1st, 0th, 17th5,7
yy44, 01, 00, 175
yyy044, 001, 1900, 20175
yyyy0044, 0001, 1900, 20175
yyyyy...3,5
Local week-numbering yearY44, 1, 1900, 20175
Yo44th, 1st, 1900th, 2017th5,7
YY44, 01, 00, 175,8
YYY044, 001, 1900, 20175
YYYY0044, 0001, 1900, 20175,8
YYYYY...3,5
ISO week-numbering yearR-43, 0, 1, 1900, 20175,7
RR-43, 00, 01, 1900, 20175,7
RRR-043, 000, 001, 1900, 20175,7
RRRR-0043, 0000, 0001, 1900, 20175,7
RRRRR...3,5,7
Extended yearu-43, 0, 1, 1900, 20175
uu-43, 01, 1900, 20175
uuu-043, 001, 1900, 20175
uuuu-0043, 0001, 1900, 20175
uuuuu...3,5
Quarter (formatting)Q1, 2, 3, 4
Qo1st, 2nd, 3rd, 4th7
QQ01, 02, 03, 04
QQQQ1, Q2, Q3, Q4
QQQQ1st quarter, 2nd quarter, ...2
QQQQQ1, 2, 3, 44
Quarter (stand-alone)q1, 2, 3, 4
qo1st, 2nd, 3rd, 4th7
qq01, 02, 03, 04
qqqQ1, Q2, Q3, Q4
qqqq1st quarter, 2nd quarter, ...2
qqqqq1, 2, 3, 44
Month (formatting)M1, 2, ..., 12
Mo1st, 2nd, ..., 12th7
MM01, 02, ..., 12
MMMJan, Feb, ..., Dec
MMMMJanuary, February, ..., December2
MMMMMJ, F, ..., D
Month (stand-alone)L1, 2, ..., 12
Lo1st, 2nd, ..., 12th7
LL01, 02, ..., 12
LLLJan, Feb, ..., Dec
LLLLJanuary, February, ..., December2
LLLLLJ, F, ..., D
Local week of yearw1, 2, ..., 53
wo1st, 2nd, ..., 53th7
ww01, 02, ..., 53
ISO week of yearI1, 2, ..., 537
Io1st, 2nd, ..., 53th7
II01, 02, ..., 537
Day of monthd1, 2, ..., 31
do1st, 2nd, ..., 31st7
dd01, 02, ..., 31
Day of yearD1, 2, ..., 365, 3669
Do1st, 2nd, ..., 365th, 366th7
DD01, 02, ..., 365, 3669
DDD001, 002, ..., 365, 366
DDDD...3
Day of week (formatting)E..EEEMon, Tue, Wed, ..., Sun
EEEEMonday, Tuesday, ..., Sunday2
EEEEEM, T, W, T, F, S, S
EEEEEEMo, Tu, We, Th, Fr, Su, Sa
ISO day of week (formatting)i1, 2, 3, ..., 77
io1st, 2nd, ..., 7th7
ii01, 02, ..., 077
iiiMon, Tue, Wed, ..., Sun7
iiiiMonday, Tuesday, ..., Sunday2,7
iiiiiM, T, W, T, F, S, S7
iiiiiiMo, Tu, We, Th, Fr, Su, Sa7
Local day of week (formatting)e2, 3, 4, ..., 1
eo2nd, 3rd, ..., 1st7
ee02, 03, ..., 01
eeeMon, Tue, Wed, ..., Sun
eeeeMonday, Tuesday, ..., Sunday2
eeeeeM, T, W, T, F, S, S
eeeeeeMo, Tu, We, Th, Fr, Su, Sa
Local day of week (stand-alone)c2, 3, 4, ..., 1
co2nd, 3rd, ..., 1st7
cc02, 03, ..., 01
cccMon, Tue, Wed, ..., Sun
ccccMonday, Tuesday, ..., Sunday2
cccccM, T, W, T, F, S, S
ccccccMo, Tu, We, Th, Fr, Su, Sa
AM, PMa..aaAM, PM
aaaam, pm
aaaaa.m., p.m.2
aaaaaa, p
AM, PM, noon, midnightb..bbAM, PM, noon, midnight
bbbam, pm, noon, midnight
bbbba.m., p.m., noon, midnight2
bbbbba, p, n, mi
Flexible day periodB..BBBat night, in the morning, ...
BBBBat night, in the morning, ...2
BBBBBat night, in the morning, ...
Hour 1-12h1, 2, ..., 11, 12
ho1st, 2nd, ..., 11th, 12th7
hh01, 02, ..., 11, 12
Hour 0-23H0, 1, 2, ..., 23
Ho0th, 1st, 2nd, ..., 23rd7
HH00, 01, 02, ..., 23
Hour 0-11K1, 2, ..., 11, 0
Ko1st, 2nd, ..., 11th, 0th7
KK01, 02, ..., 11, 00
Hour 1-24k24, 1, 2, ..., 23
ko24th, 1st, 2nd, ..., 23rd7
kk24, 01, 02, ..., 23
Minutem0, 1, ..., 59
mo0th, 1st, ..., 59th7
mm00, 01, ..., 59
Seconds0, 1, ..., 59
so0th, 1st, ..., 59th7
ss00, 01, ..., 59
Fraction of secondS0, 1, ..., 9
SS00, 01, ..., 99
SSS000, 001, ..., 999
SSSS...3
Timezone (ISO-8601 w/ Z)X-08, +0530, Z
XX-0800, +0530, Z
XXX-08:00, +05:30, Z
XXXX-0800, +0530, Z, +1234562
XXXXX-08:00, +05:30, Z, +12:34:56
Timezone (ISO-8601 w/o Z)x-08, +0530, +00
xx-0800, +0530, +0000
xxx-08:00, +05:30, +00:002
xxxx-0800, +0530, +0000, +123456
xxxxx-08:00, +05:30, +00:00, +12:34:56
Timezone (GMT)O...OOOGMT-8, GMT+5:30, GMT+0
OOOOGMT-08:00, GMT+05:30, GMT+00:002
Timezone (specific non-locat.)z...zzzGMT-8, GMT+5:30, GMT+06
zzzzGMT-08:00, GMT+05:30, GMT+00:002,6
Seconds timestampt5129695207
tt...3,7
Milliseconds timestampT5129695209007
TT...3,7
Long localized dateP04/29/14537
PPApr 29, 14537
PPPApril 29th, 14537
PPPPFriday, April 29th, 14532,7
Long localized timep12:00 AM7
pp12:00:00 AM7
ppp12:00:00 AM GMT+27
pppp12:00:00 AM GMT+02:002,7
Combination of date and timePp04/29/1453, 12:00 AM7
PPppApr 29, 1453, 12:00:00 AM7
PPPpppApril 29th, 1453 at ...7
PPPPppppFriday, April 29th, 1453 at ...2,7

See https://date-fns.org/v2.23.0/docs/format for more details.

Localization

Element's datepicker now supports i18n localization. We include all of the languages supported by date-fns including:

af, arDZ, arMA, arSA, arTN, az, be, bg, bn, bs, ca, cs, cy, da, de, deAT, el, enAU, enCA, enGB, enIN, enNZ, enUS, enZA, eo, es, et, eu, faIR, fi, fr, frCA, frCH, gd, gl, gu, he, hi, hr, ht, hu, hy, id, is, it, ja, ka, kk, kn, ko, lb, lt, lv, mk, mn, ms, mt, nb, nl, nlBE, nn, pl, pt, ptBR, ro, ru, sk, sl, sq, sr, srLatn, sv, ta, te, th, tr, ug, uk, uz, vi, zhCN, zhTW.

Using a locale

import { de } from 'date-fns/locale';

<Datepicker locale={de}>

Datepicker Props

NameTypeDefaultRequiredDescription
alwaysOpenbooleanfalsefalseKeep the calendar visible at all times.
calendarPropsobjectundefinedfalseCustom props to be passed to the calendar.
calendarTypestring'full'falseDefine the type of the calendar. full defaults to the dd MMM yyyy date format, month-year defaults to the MMM yyyy date formatAccepted Values: full, month-year
centuryBehaviorstring'age'falseWhen typing a date, this will determine 2-digit year parsing behavior. A value of forward-only will always use current century, so 02/08/02 will parse to 02/08/2002. A value of age, on the other hand is meant to assist age entry. It will use the current century until a certain point (see centurySlidingOffset), and then will revert to the previous century. For example 05/25/01 will parse to 05/25/2001, while 02/08/76 will parse to 02/08/1976.Accepted Values: age, forward-only
centurySlidingOffsetnumber76falseOnly used when centuryBehavior is set to age. This will adjust the cutoff point where 2 digit dates will revert to the previous century to aid in typed age entry. The formula for the cutoff is last 2 digits of the result of current year minus centuryCutoffOffset. For example, using the year 2022 and the default value of 76 we would have lastTwoDigits(2022 - 76) = 46. So any 2 digit year of 45 or less will become 20XX and any 2 digit year of 46 or more will become 19XX. A value of 0 will disable the behavior, regardless of centuryBehavior. In 2023, the cutoff will be 47, and so forth.
classNamestringundefinedfalseThe css class name to be passed through to the component markup.
dayCellTemplatefunctionday => day.datefalseA function for formatting the individual days of the calendar. It takes the date being rendered and returns content.
disableChangeMonthbooleanfalsefalsePrevents the user from changing the month. Often used in conjunction with disableChangeYear to allow the user to only choose a date within the current month.
disableChangeYearbooleanfalsefalsePrevents the user from changing the year. Often used in conjunction with disableChangeMonth to allow the user to only choose a date within the current month.
disableClearingbooleanfalsefalsePrevent the datePicker from being cleared. It is suggested to use readOnly in conjunction with disableClearing.
disabledbooleanfalsefalseIf true, disable datePicker completely.
disabledDatesObjectundefinedfalseAn object describing dates to be disabled and non-interactive. The schema includes the following: { dates, days, daysOfMonth, from, to, ranges, customPredictor }. Please see README for full schema description and examples. Note: All dates are inclusive and date comparisons ignore time.
formatstring|function'dd MMM yyyy'falseDate formatting string or function. For format strings we use date-fns.format(). See https://date-fns.org/v2.23.0/docs/format for more details.
fullMonthNamebooleantruefalseDisplay the full month name in the calendar interface. Note, this does not effect the date format.
highlightedDatesObjectundefinedfalseAn object describing dates to be highlighted. The schema includes the following: { includeDisabled, dates, days, daysOfMonth, from, to, ranges, customPredictor }. Please see README for full schema description and examples. Note: All dates are inclusive and date comparisons ignore time.
hoistedbooleanundefinedfalseControls if the component is rendered outside of the parent element (aka hoisted). This is now managed automatically and no longer needs to be explicitly set unless using a custom (non-element) components with a parent that has overflow: hidden.
idstringundefinedfalseRandomly generated id. May be overwritten.
inputTimeZonestringundefinedfalseThe timezone that the input date is provided in (see value). If outputTimeZone is not set, the date will be returned as UTC. Supports international timezones. See https://www.iana.org/time-zones.
labelstringundefinedfalseThe input label.
localeobjectenUSfalseLanguage support object in the i18n format. A number of pre-built languages can be imported from the npm package date-fns.
maxDateDateundefinedfalseThe maximum date selectable. Dates later than this will be disabled.
maxQuickSelectYearnumberundefinedfalseThe maximum year that will be visible in the year select dropdown. Note, This does not disable dates later than this from being able to be selected (see minDate), it only affects what years are visible in the Select. Defaults to current year + 10.
minDateDateundefinedfalseThe minimum date selectable. Dates earlier than this will be disabled.
minQuickSelectYearnumberundefinedfalseThe minimum year visible in the year select dropdown. Note, This does not disable dates earlier than this from being able to be selected (see minDate), it only affects what years are visible in the Select. Defaults to current year - 10.
mondayFirstbooleanfalsefalseOverrides the first day of the week to start on Monday.
openDatedateundefinedfalseIf set, open on that date. Must be either a valid date object or a string that can be parsed by the date constructor.
outputTimeZonestringundefinedfalseThe timezone the date will be converted to and formatted as when using useUtc. If inputTimeZone is not set, the date is assumed to already be in UTC time. Supports international timezones. See https://www.iana.org/time-zones.
parseFormatsstring"P"falseOne or more acceptable formats for typed input. The default value 'P' will accept a short locale formatted date. See https://date-fns.org/v2.28.0/docs/parse for parsing options. Note, the value of the format prop will automatically be accepted.
placeholderstringundefinedfalsePlaceholder text for the input.
portalContainerstring|React.ReactNode'document.body'falseThe DOM element the children will render in. If a string is sent it should be a valid DOM query selector. If one is not sent, Portal will default to document.body.
readOnlybooleanfalsefalseUser will not be allowed to type the date and must select it from the calendar.
requiredbooleanfalsefalseSets html required attribute on input
resetCalendarOnClosebooleanfalsefalseThis will reset the Calendar view to the selected date (or today's date when no date has been selected). By default the calendar will remember the last visible date shown until the page is refreshed.
sideContentobject|string|functionundefinedfalseContent to appear to the side of the Calendar. Can be used to display details for a selected date. Normally will appear to the right of the calendar, except when rtl is true, where it will appear to the left of the calendar.
textfieldPropsobjectundefinedfalseProps to be passed to the Textfield component. Accepts any valid Textfield props.
useUtcbooleanfalsefalseUse UTC for time calculations.
valuedateundefinedfalseCurrent value of the datePicker.
variantstring'filled'falseApplies the selected style to the internal textfield.Accepted Values: filled, outlined

Datepicker Deprecated Props

NameTypeDefaultRequiredDeprecatedDescription
filledbooleanundefinedfalseUse variant='filled' instead.Apply filled style to the date picker input. Previously called primary.
outlinedbooleanundefinedfalseReplaced by variant='outlined'Apply outlined style to the date picker input. Previously called secondary.
primarybooleanundefinedfalseReplaced by variant='outlined'Applies a filled style.
secondarybooleanundefinedfalseReplaced by variant='outlined'Applies outlined style.
typeablebooleanundefinedfalsePlease use readOnly instead.The user will not be allowed to type the date and must select it from the calendar.

Datepicker Render Props

NameTypeDefaultRequiredDescription
headerContentReact.ReactNodeundefinedfalseContent to appear immediately after the Calendar header.
leadingContentReact.ReactNodeundefinedfalseContent to appear before the Calendar header.
trailingContentReact.ReactNodeundefinedfalseContent to appear after the Calendar.

Datepicker Deprecated Render Props

NameTypeDefaultRequiredDeprecatedDescription
beforeCalendarHeaderReact.ReactNodeundefinedfalseUse leadingContent instead.Content to appear before the header.

Datepicker Events

NameDefaultRequiredParamsDescription
onChangeundefinedfalseFired when character is entered into text field and on select.
onClearundefinedfalseFired when input is cleared with the 'x' button.
onCloseundefinedfalseFired when calendar is closed.
onOpenundefinedfalseFired when calendar is opened.
onSelectundefinedfalseFired when date is selected.
onSelectDisabledundefinedfalseFired when disabled date is clicked
onSelectMonthundefinedfalseFired when month is selected
onSelectYearundefinedfalseFired when year is selected

Datepicker Deprecated Events

NameDefaultRequiredParamsDeprecatedDescription
onSelectDisableundefinedfalseThis has been renamed to onSelectDisabled for consistencyFired when disabled date is clicked

Datepicker Breaking Changes

Description
dayCellContent (removed): Renamed to dayCellTemplate.
format: date-fns uses different tokens than the previous version of Datepicker, format strings may need to be updated.
highlighted (removed): Renamed to highlightedDates
initialView (removed): No longer used.
inline (removed): Use alwaysOpen instead.
localization (removed): Use locale instead.
maximumView (removed): Use disabledDates.
minimumView (removed): Use disabledDates.

Calendar Props

NameTypeDefaultRequiredDescription
classNamestringundefinedfalseThe css class name to be passed through to the component markup.
dayCellTemplatefunctionday => day.datefalseA function for formatting the individual days of the calendar. It takes the date being rendered and returns content.
disableChangeMonthbooleanfalsefalsePrevents the user from changing the month. Often used in conjunction with disableChangeYear to allow the user to only choose a date within the current month. An alternative to disabled dates.
disableChangeYearbooleanfalsefalsePrevents the user from changing the year. Often used in conjunction with disableChangeMonth to allow the user to only choose a date within the current year. An alternative to disabled dates.
disabledDatesObjectundefinedfalseOne or more date ranges that are not selectable. Must be in the format: {ranges: [{ from, to }]} where from/to are valid javascript date objects.
floatingbooleantruefalseMake the calendar float using absolute positioning.
fullMonthNamebooleantruefalseTo show the full month name.
highlightedDatesObjectundefinedfalseAn object describing pre-highlighted dates of the currently visible month. The object can include the following fields: includeDisabled = include dates that are outside of the current month in the highlighting. dates = an array of valid date objects to highlight, most useful for scattered highlighted dates. from and to = a valid start and end date range to highlight, most useful for a contiguous block of highlighted dates.
hoistedbooleanundefinedfalseControls if the component is rendered outside of the parent element (aka hoisted). This is now managed automatically and no longer needs to be explicitly set unless using a custom (non-Element) component with a parent that has overflow: hidden.
isRtlbooleanfalsefalseThe current language is right-to-left.
localeobjectenUSfalseLanguage support object in the i18n format. A number of pre-built languages can be imported from the npm package date-fns.
maxDateDateundefinedfalseThe maximum date selectable. Dates later than this will be disabled.
maxQuickSelectYearnumberundefinedfalseNote, This does not disable dates later than this from being able to be selected (see minDate), it only affects what years are visible in the Select. Defaults to current year + 10.
minDateDateundefinedfalseThe minimum date s