2.16.9 • Published 5 years ago

@dorgaren/react-vs-calendar v2.16.9

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

react-vs-calendar

A date and time picker component that is compatible with React and Preact. Uses moment.js. Strives to be downwards-compatible with ES5.

Forked from https://github.com/YouCanBookMe/react-datetime since the last accepted merge request is some 9 months ago with lots piling already.

Installation

Install using npm:

npm install --save @dorgaren/react-vs-calendar

Install using yarn:

yarn add @dorgaren/react-vs-calendar

Usage

React.js (or Preact with preact-compat or PreactX) and Moment.js are peer dependencies for react-vs-calendar (as well as Moment.js timezones if you want to use the displayTimeZone prop). These dependencies are not installed along with react-vs-calendar automatically, but your project needs to have them installed in order to make the calendar work. You can then use the control like in the example below.

const Calendar = require("@dorgaren/react-vs-calendar");

...

render: function()
{
    return <Calendar />;
}

TODO: add examples

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
viewDateDatenew Date()Represents the month which is viewed on opening the calendar when there is no selected date. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
staticbooleanfalse when input is true, true otherwiseWhether to show the calendar as statically positioned.
openbooleannullWhether to open or close the picker. If not set react-vs-calendar will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-vs-calendar instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
displayTimeZonestringnullNeeds moment's timezone available in your project. When specified, input time values will be displayed in the given time zone. Otherwise they will default to the user's local timezone (unless utc specified).
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
onNavigateBackfunctionempty functionCallback trigger when the user navigates to the previous month, year or decade. The callback receives the amount and type ("month", "year") as parameters.
onNavigateForwardfunctionempty functionCallback trigger when the user navigates to the next month, year or decade. The callback receives the amount and type ("month", "year") as parameters.
viewModestring or number"days"The default view to display when the picker is shown ("years", "months", "days", "time").
classNamestring or string array""Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (className sets the class attribute for the input element). See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderInputfunctionundefinedReplace the rendering of the input element. The function has the following arguments: the default calculated props for the input, openCalendar (a function which opens the calendar) and closeCalendar (a function which closes the calendar). Must return a React component or null. See Customize the Input Appearance.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleantrueWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableCloseOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.

i18n

Different language and date formats are supported by react-vs-calendar. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

var moment = require("moment");
require("moment/locale/fr");
// Now react-vs-calendar will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Calendar locale="fr-ca" />
<Calendar locale="de" />

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<Calendar inputProps={{ placeholder: "N/A", disabled: true }}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

var CustomCalendar = React.createClass({
    render: function()
    {
        return <Calendar renderInput={ this.renderInput } />;
    },
    renderInput: function(props, openCalendar, closeCalendar)
    {
        function clear()
        {
            props.onChange({ target: { value: "" } });
        };

        return (
            <div>
                <input { ...props } />
                <button onClick={ openCalendar }>open calendar</button>
                <button onClick={ closeCalendar }>close calendar</button>
                <button onClick={ clear }>clear</button>
            </div>
        );
    }
});

Customize the appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

var CustomCalendar = React.createClass({
    render: function()
    {
        return <Calendar
            renderDay={ this.renderDay }
            renderMonth={ this.renderMonth }
            renderYear={ this.renderYear }
        />;
    },
    renderDay: function(props, currentDate, selectedDate)
    {
        return <td { ...props }>{ "0" + currentDate.date() }</td>;
    },
    renderMonth: function(props, month, year, selectedDate)
    {
        return <td { ...props }>{ month }</td>;
    },
    renderYear: function(props, year, selectedDate)
    {
        return <td { ...props }>{ year % 100 }</td>;
    }
});

Method Parameters

  • props is the object that the control has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<Calendar dateFormat={ false } />

In this example you can only select a year and month.

<Calendar dateFormat="YYYY-MM" timeFormat={ false } />

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime component
var yesterday = Datetime.moment().subtract(1, "day");
var valid = function(current)
{
    return current.isAfter(yesterday);
};
<Calendar isValidDate={ valid } />

It's also possible to disable the weekends, as shown in the example below.

var valid = function( current ){
    return current.day() !== 0 && current.day() !== 6;
};
<Calendar isValidDate={ valid } />

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-vs-calendar.d.ts and typings for 2.0 are found in typings/index.d.ts.

import * as Calendar from "@dorgaren/react-vs-calendar";

class CustomCalendar extends React.Component<CalProps, CalState>
{
    render() JSX.Element { return <Calendar />; }
}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-vs-calendar-playground.

Changelog

MIT Licensed