Datepicker

The Datepicker component is the ultimate tool for selecting a single date and/or time, multiple dates or a date range.

Basic usage

The following example will create a datepicker with the default options.

By default the datepicker will be set up to single date selection with the calendar control.

JSX
import { Datepicker } from '@mobiscroll/react';

const App = () => {
  return <Datepicker />;
}

For many more examples - simple and complex use-cases - check out the date picker demos for react.

Value Selection

The datepicker can be used for three major dates and time selection tasks:

  1. Single value selection - a date, time or date-time - use the date & time or calendar
  2. Multiple value selection - one or more dates - use the date picker or calendar
  3. Range selection - a pair of start/end date, time or date-times - use the range picker
    1. Preset range selection - for selecting a week or a predefined part of the week
The select and selectMultiple options control how the selection works. Also with the firstSelectDay and selectSize options the selection can be tailored further, when using the preset-range selection.

Single Value Selection

This is the default behavior, and it can also be initialized with the select: 'date' option. Depending on the controls option, we can use the datepicker this way to select either a single date or a single time or both (a single datetime).

Date picker
const App = () => {
    const [myBirthday, setMyBirthday] = React.useState(null);
    const pickerChange = (ev) => {
        setMyBirthday(ev.value);
    }
    return <Datepicker select="date" value={myBirthday} onChange={pickerChange} />;
}

Multiple Value Selection

The selectMultiple option will enable us to select multiple dates on the calendar. The selected value in this case will be an array of dates instead of just a single date.

Multiple date picker
const App = () => {
    const [myCleaningDays, setMyCleaningDays] = React.useState(null);
    const pickerChange = (ev) => {
        setMyCleaningDays(ev.value);
    }
    return <Datepicker selectMultiple={true} value={myCleaningDays} onChange={pickerChange} />;
}

Range Selection

The datepicker can be used to select a date or a time range. The range selection feature can be activated with the select: 'range' option. The selected value in this case will be an array of dates with two values: the start and the end.

The controls option will tell the datepicker what kind of range do we want to select, a date range or a time range.

Date Range Picker
const App = () => {
    const [myHoliday, setMyHoliday] = React.useState(null);
    const pickerChange = (ev) => {
        setMyHoliday(ev.value);
    }
    return <Datepicker select="range" value={myHoliday} onChange={pickerChange} />;
}

Preset-range Selection

The datepicker can be used to select a week or predefined part of the week. The preset-range selection feature can be activated with the select: 'preset-range' option. The selected value in this case will be an array of dates with two values: the start and the end of the range.

When the preset-range selection mode is on the start date will be fixed to a specific day of the week (for example: Monday). This can be achieved with the firstSelectDay option, which defaults to the firstDay of the week.

The length of the selection will be a set number of days (for example: 5 days) and can be controlled with the selectSize option. By default it is set to 7 (will select the whole week), but can be further reduced to even a single day.

Week select example
const App = () => {
    const [myWeek, setMyWeek] = React.useState(null);
    const pickerChange = (ev) => {
        setMyWeek(ev.value);
    }
    return <Datepicker select="preset-range" value={myWeek} onChange={pickerChange} />;
}

The follwing example will create a datepicker that selects working days for a week (from Monday to Friday):

Work week example
const App = () => {
    const [myWeek, setMyWeek] = React.useState(null);
    const pickerChange = (ev) => {
        setMyWeek(ev.value);
    }
    return <Datepicker select="preset-range" firstSelectDay={1} selectSize={5} value={myWeek} onChange={pickerChange} />;
}

Return values

The default type of return values is the JavaScript Date object, but Mobiscroll supports more types as well. The Datepicker will choose the type depending on the returnFormat option.

Here's a list on supported formats and some hints on where are they really usefull:

When working with 'moment', you need to ensure that your project includes the Moment.js library and also you will need to pass the moment libary reference to the Datepicker. Here's an example how:

Passing the reference of the moment to the Datepicker
import * as moment from 'moment';

function App() {
    const [myValue, setMyValue] = React.useState(moment());
    const myChange = (ev) => {
        setMyValue(ev.value); // ev.value is a Moment object
    }
    return <Datepicker moment={moment} returnFormat="moment" onChange={myChange} value={myValue} />
}

Timezones

By default the Datepicker uses the local timezone of the browser for value selection. If you want to select a date-time in a different timezone, you will need an external library to handle the timezone conversions. There are two libraries that Mobiscroll supports: moment-timezone and luxon.

When using a timezone plugin with the Datepicker, the returned values are always ISO 8601 date strings, no matter what returnFormat option is used.
When using a timezone plugin with the Datepicker, the exclusiveEndDates options defaults to true. Learn more about exclusive end dates here!

Library Install

To setup the library, first you have to install it on your page. In this guide we'll assume you are using npm to install packages, but you can consult the installation guide on the libraries official pages (moment-timezone install page, luxon install page) for more options on how to install them.

The Moment-Timezone library

To install the moment-timezone library with npm you will need to run the following commands:

$ npm install moment-timezone

After the library is installed, you will have to import it with the momentTimezone object from mobiscroll:

import moment from 'moment-timezone';
import { momentTimezone } from '@mobiscroll/react';

Then set the mobiscroll's reference to the imported library:

momentTimezone.moment = moment;

After that, you can pass the momentTimezone object to the Datepicker's timezonePlugin option.

The Luxon library

To install the luxon library with npm you will need to run the following commands:

$ npm install luxon

In case you are using typescript you can also consider installing the types, because they come separately:

$ npm install --save-dev @types/luxon

After the library is installed, you will have to import it with the luxonTimezone object from mobiscroll:

import * as luxon from 'luxon';
import { luxonTimezone } from '@mobiscroll/react';

Then set the mobiscroll's reference to the imported library:

luxonTimezone.luxon = luxon;

After that, you can pass the luxonTimezone object to the Datepicker's timezonePlugin option.

Example with timezones

Example
import moment from 'moment-timezone';
import { momentTimezone, Datepicker } from '@mobiscroll/react';

// setup the reference to moment
momentTimezone.moment = moment;
        
function App() {
    return <Datepicker timezonePlugin={momentTimezone} dataTimezone="utc" displayTimezone="Europe/Berlin" />;
}

Exclusive end dates

The problem with end dates

To understand why we need exclusive end dates support, we need to look at what dates and date ranges represent.

Javascript date objects (and ISO8601 date strings - no matter the format) technically represent a point in time. A date range on the other hand is a duration between two points in time (the start of the range and the end of the range).

The problem comes when we want to translate between the daily language to the technical world. For example, when we say "I'm on holiday from the 21st until the 27th of July" we refer to this range as

'2022-07-21 - 2022-07-27'

Technically this range ends at the first moment on the 27th of July, because 2022-07-27 is the same as 2022-07-27T00:00:00.000. But we think of it as the whole day, meaning I'm still on holiday on the 27th (and expect my colleages not to bother me with work).

The correct and precise timestamps for the above range, which I actually mean is the following:

'2022-07-21T00:00:00.000 - 2022-07-27T23:59:59.999'

To work with this end date is a bit awkward and because of that also error prone. It's not easily readable and also causes calculation headaches. For example if we try to calculate how long is this vacation (duration = end - start) we get 7 days minus 1 millisecond.

The solution to end dates

The solution to this problem is the exclusiveEndDates option. When this options is true and we select dates only, without time part, we always exclude the end date from the range.

To keep going with the above example, the selected range will be:

'2022-07-21 - 2022-07-28'

In terms of UX, the user should not have to think about all that, so the Datepicker will show the correct range for them.
On the calendar for example, the highlighted range will still be 21st-27th, but the returned dates will be 21st and 28th.

Enabling exclusive end dates can cause breaking changes. The invalid, labels, marked and colors options all can be specified with date ranges, and these ranges will be interpreted according to the exclusiveEndDate option.

With inclusive end dates an invalid with start: '2021-07-09' and end: '2021-07-10' will disable two days on the calendar, the 9th and 10th of July. With exclusive end dates only a single day will be disabled, the 9th of July.

Controls

The datepicker component can render different kinds of controls on the screen. These controls are referred to as the Calendar view, the Date picker, the Time picker, the Datetime picker and the Timegrid. Each of these controls are suitable in different scenarios, depending on the use-case.

For example, the Date picker can be used for selecting a single date, as well as the Calendar view. But only the Calendar view can be used for selecting multiple dates.

Single vs. Multiple Date selection
const App = () => {
    const [myBirthday, setMyBirthday] = React.useState(null);
    const myPickerChange = (ev) => {
        setMyBirthday(ev.value);
    }
    const [kidsBirthday, setKidsBirthday] = React.useState(null);
    const kidsPickerChange = (ev) => {
        setMyBirthday(ev.value);
    }
    return <>
        <Datepicker controls={['date']} value={myBirthday} onChange={myPickerChange} />
        <Datepicker controls={['calendar']} selectMultiple={true} value={kidsBirthday} onChange={kidsPickerChange} />
    </>;
}

Control combinations

Some controls can't be used in all situations. To have a better user experience, controls can be combined. The controls options takes an array of strings, with predefined values.

The Time picker and the Timegrid controls can be combined with either the Calendar view or the Date picker for extending the selection precision.

Combined controls
const App = () => {
    const [myAppointment, setMyAppointment] = React.useState(null);
    const myPickerChange = (ev) => {
        setMyAppointment(ev.value);
    }
    return <>
        <!-- Date & Time picker -->
        <Datepicker controls={['date', 'time']} value={myAppointment} onChange={myPickerChange} />
        <!-- Calendar view & Time picker -->
        <Datepicker controls={['calendar', 'time']} value={myAppointment} onChange={myPickerChange} />
        <!-- Date & Timegrid -->
        <Datepicker controls={['date', 'timegrid']} value={myAppointment} onChange={myPickerChange} />
        <!-- Calendar view & Timegrid -->
        <Datepicker controls={['calendar', 'timegrid']} value={myAppointment} onChange={myPickerChange} />
    </>;
}

Customizing the Input

The datepicker, as explained below, can be used with one, two or no inputs.

Using without inputs

The first choice of input customization is to have no inputs at all. In this case rendering the component in inline display mode will leave out the use of inputs.

Inline picker
const App = () => {
    const [myAppointment, setMyAppointment] = React.useState(null);
    const myPickerChange = (ev) => {
        setMyAppointment(ev.value);
    }
    return <Datepicker display="inline" value={myAppointment} onChange={myPickerChange} />;
}

Using with one input

The datepicker component will render a Mobiscroll Input by default. This input will hold the formatted value after selection.

Using a custom input can be done with the inputComponent prop. In this case the datepicker will render the component provided and pass the formatted value to it.

To pass props to the custom component, you can use the inputProps prop.

Using IonInput as a Custom Input
import { IonInput, IonItem } from '@ionic/react';

const app = () => {
  const ionInputProps = {
    placeholder: 'Click to select',
    readOnly: true,
  };

  return <IonItem>
       <Datepicker inputComponent={IonInput} inputProps={ionInputProps} />
    </IonItem>;
}

Using with two inputs

When selecting a range, you have basically two values to display: the start of the range and the end of the range. These can be shown in different inputs using the startInput and the endInput options.

Two inputs for range selection
import { Input, Datepicker } from '@mobiscroll/react';

const app = () => {
  const [start, setStartInput] = React.useState(null);
  const [end, setEndInput] = React.useState(null);

  return <>
      <Input ref={setStartInput} label="Start date" />
      <Input ref={setEndInput} label="End date" />
      <Datepicker select="range" startInput={start} endInput={end} />
    </>;
}

When the startInput and the endInput options are provided, the datepicker will not render any other inputs. It will open when these inputs are focused/clicked instead.

Display modes

The datepicker component can operate in two ways from the display option's point of view:

Here comes the center, top, bottom displays, and also the anchored display when the touchUi option is true.

In these display modes, the picker shows up as a modal picker. When open, the selected value is stored as a temporary value until the set button is pressed. At that point the picker is closed and the value is commited to the state.

The above mentioned temporary value, when required, can be manipulated using the getTempVal() and setTempVal() instance methods. Whe the temporary value changes the onTempChange event is raised.

"Live" selection

Here come the inline display (which displays as an embedded control) and the anchored display when the touchUi options is false (on desktop devices).

In this case by default there is no set button to commit the value, so there's no temporary value like when the modal displays are used. What is shown on the picker, that is set directly to the state

Recurrence

For the colors, labels, marked, valid and invalid options it's possible to specify recurrence rules. The rule can be an object or a string in RRULE format.

Supported properties:

In string format the specified properties are separated by the ';' character.

As object
recurring: {
  repeat: 'daily',
  count: 5,
  interval: 2
}
As string
recurring: 'FREQ=DAILY;COUNT=5;INTERVAL=2'

Examples

JSX
import { Datepicker } from '@mobiscroll/react';

const App = () => {
    const myInvalids = useMemo(() => [{
        start: '00:00',
        end: '08:59',
        recurring: {
            repeat: 'daily'
        }
    }, {
        start: new Date(2020, 2, 18, 9, 0),
        end: new Date(2020, 2, 18, 17, 0),
        recurring: {
            repeat: 'daily',
            count: 5,
            interval: 2
        }
    }, {
        start: new Date(2020, 2, 17, 20, 0),
        end: new Date(2020, 2, 17, 22, 0),
        recurring: 'FREQ=WEEKLY;UNTIL=2020-06-17;BYDAY=MO,WE'
    }], []);
    return <Datepicker invalid={myInvalids} />;
}

Recurring exceptions

In case you would like to skip some dates from your rule, that's when the recurring exception come in handy. You can either set specific dates and/or a recurring rule as an exception, using the recurringException and the recurringExceptionRule properties.

JSX
import { Datepicker } from '@mobiscroll/react';

const App = () => {
    const myInvalids = useMemo(() => [{
        start: '2021-06-01',
        end: '2021-06-01'
        recurring: {
            repeat: 'daily',
            until: '2021-12-31'
        },
        // exact dates as exceptions
        recurringException: ['2021-07-10', '2021-07-11'],
        // recurring rule as an exception
        recurringExceptionRule: {
            repeat: 'monthly',
            day: 15
        }
    }, {
        start: '08:30',
        end: '10:00',
        // Every Monday and Friday, except every second month\'s 3rd',
        recurring: 'FREQ=WEEKLY;UNTIL=2021-06-01;BYDAY=MO,FR',
        recurringExceptionRule: 'FREQ=MONTHLY;BYMONTHDAY=3;INTERVAL=2'
    }], []);
    return <Datepicker invalid={myInvalids} />;
}

Customizing the calendar header

The header of the calendar can be fully customized to one's needs. This can be achieved by passing a function that returns the custom header to the renderCalendarHeader option.

Fully custom header
const customTemplate = () => {
    return <>
        <p>Any <strong>Title</strong> you want here or</p>
        <YourCustomComponent yourProp="yourPropValue" />
    </>
}
<Datepicker renderCalendarHeader={customTemplate} />

While fully customizing the header is very usefull, sometimes it's desireable to customize only parts of it. In this case you can take advantage of the default header's building blocks. These components let you put toghether the header you want, while you don't have to worry about the functionality behind them.
For example you can leave out parts from the default header, change the order the default buttons appearance or add custom components between them.

Here's the list of the built in components of the default header:

The above components can be used inside of the custom header. The following example will render the prev and next buttons and then a custom title that is set from a custom variable (myTitle variable).

Custom header with default buttons
const myTitle = 'My Awesome title';
const customWithNavButtons = () => {
    return <>
        <CalendarPrev />
        <CalendarNext />
        <div className="my-custom-title">{myTitle}</div>
    </>;
}

<Datepicker renderCalendarHeader={customWithNavButtons} />

Options

Name Type Default value Description
anchor HTMLElement undefined Specifies the anchor element for positioning, if display is set to 'anchored' . If undefined, it defaults to the element on which the component was initialized.
animation String, Boolean undefined Animation to use for opening/closing of the control (if display is not inline). Possible values:
  • 'pop'
  • 'slide-down'
  • 'slide-up'
If false, turns the animation off.
buttons Array ['set', 'cancel'] Buttons to display. Each item in the array will be a button. A button can be specified as a string, or as a button object.

When the passed array does not contain the predefined 'set' button, the auto-selection will be turned on. Selecting a value on the UI this way, will be set to the input immediately. If there are more than one wheels shown, the control will close on overlay tap. Otherwise tapping a value on the wheel will also close the control.

If a string, it must be one of the predefined buttons:
  • 'set' - Sets the value.
  • 'cancel' - Dismisses the popup.
To modify the text of the predefined buttons, you can use the setText, , cancelText options.

If an object, it may have the following properties:
  • text String - Text of the button.
  • handler String, Function - The function which will run when the button is pressed. If a string, it must be one of the predefined button handlers:
    • 'set' - Sets the value.
    • 'cancel' - Dismisses the popup.
  • icon String (Optional) - Icon of the button.
  • cssClass String (Optional) - Css class of the button.
  • keyCode Number, String, Array (Optional) - The key code associated with the button to activate it from keyboard. Can be a single value or multiple value passed as an array. Predifine string values are: 'enter', 'esc' and 'space'.
Predefined and custom buttons example
buttons: [
    'set',
    {
        text: 'Custom',
        icon: 'checkmark',
        cssClass: 'my-btn', 
        handler: function (event) {
            alert('Custom button clicked!');
        }
    },
    'cancel'
]
Predefined button handler example
buttons: [
    'set',
    {
        text: 'Hide',
        handler: 'cancel',
        icon: 'close',
        cssClass: 'my-btn'
    }
]
calendarScroll String 'horizontal'

Controls the direction the calendar can be navigated. You can navigate by scrolling, swiping or by clicking the arrow buttons in the header.

  • 'horizontal' - navigating the view horizontally.
  • 'vertical' - navigationg the view vertically.

When navigation is 'vertical' the outer days (days from previous and next months) are hidden. You can explicitly override it with the showOuterDays option.

calendarSize Number 1

Number of months/weeks to display.

The months/weeks start from a reference date, that can be set using the refDate option.

calendarSystem Object undefined Specify the calendar system to be used. Supported calendar systems:
  • Gregorian - This is the default calendar system, no setting needs to be passed.
  • Jalali - Default system of the Persian calendar. The Farsi language needs to be included to the package.
    import { Eventcalendar, jalaliCalendar } from '@mobiscroll/react';
    
    export function MyComponent() {
      return <Eventcalendar calendarSystem={jalaliCalendar} />;
    }
    
  • Hijri - Arabic language needs to be included to the package.
    import { Eventcalendar, hijriCalendar } from '@mobiscroll/react';
    
    export function MyComponent() {
      return <Eventcalendar calendarSystem={hijriCalendar} />;
    }
    
calendarType String 'month'

Sets the calendar type. Possible values: 'year', 'month', 'week'.

In case of 'month' set the number of displayed months using the pages option (swipeable month view) or the calendarSize option (grid month view).

In case of 'week' set the number of displayed weeks using the calendarSize option.

circular Boolean, Array undefined If true, the scroll wheels are circular. If an array, it can be specified as a per wheel configuration, e.g. for 3 wheels: [true, false, false] - sets the first wheel circular. If not specified, if a wheel has more values than the number of displayed rows, the scroll wheel becomes circular.
closeOnEsc Boolean true If true, the popup is closed on ESC keypress.
closeOnOverlayClick Boolean true If true, the popup is closed on overlay tap/click.
colors Array undefined Change the color of certain dates on the calendar. Must be an array of objects with the following properties:
  • allDay Boolean - Specifies whether the date you want to color is all day or not.
  • date Date, String, Object - Date of the calendar day which should be colored.
  • start Date, String, Object - Start date/time of the calendar days/cells which should be colored.
  • end Date, String, Object - End date/time of the calendar days/cells which should be colored.
  • background: String - Background color of the cell, can be any valid CSS color ('red', '#ff0000', 'rgb(255,0,0)', etc.).
  • highlight: String - Highlight color of the day, can be any valid CSS color ('red', '#ff0000', 'rgb(255,0,0)', etc.).
  • recurring String, Object - Recurrence rule for coloring recurring days.
  • recurringException: String, Object, Array - Recurrence exception for recurring colors.
  • recurringExceptionRule: String, Object - Recurrence exception rule for recurring colors.
  • cellCssClass: String - CSS class for the day cell. This property is only applicable in the case of the calendar view.
  • resource: String, Number, Array of String | Number - specify resource ids for the color. The color will display only in the specified resource group. If there is no resource id defined the color will be displayed at every resource group.
  • slot: String, Number - specify slot ids for the color. The color will display only in the specified slot group. If there is no slot id defined the color will be displayed at every slot group.
  • cssClass String - Specifies the custom CSS class name. This property is only applicable in the case of the scheduler and timeline view.
The colored range will be considered all-day if:
  • allDay is explicitly set.
  • start/end is not specified, only the date.
The dates can be specified as Javascript Date objects, ISO 8601 strings, or moment objects.
The colors can be combined with the labels or marked options.
Example
colors: [
    { date: new Date(2020,2,23), background: 'pink' },
    { date: new Date(2020,2,24), background: 'green' },
    { background: '#ff0000', recurring: { repeat: 'weekly', weekDays: 'SU' } },
    { background: 'yellow', recurring: { repeat: 'weekly', weekDays: 'SA' } }
]
context String, HTMLElement 'body' The DOM element in which the component is appended and positioned (if not inline). Can be a selector string or a DOM element.
controls Array ['calendar'] List of controls to show. Possible values:
  • ['calendar']
  • ['calendar', 'time']
  • ['date']
  • ['datetime']
  • ['date', 'time']
  • ['time']
  • ['timegrid']
cssClass String undefined Applies custom css class to the top level element.
dataTimezone String defaults to displayTimezone Specifies the timezone of the selected values. The selection happens in the displayTimezone, but the values will be converted to the dataTimezone before they are returned.

Also the invalid, labels, marked and colors data will be interpreted in dataTimezone if it doesn't contain timezone information already. If the data contain timezone information (when the ISO string has a timezone offset ex. "2021-03-28T01:00:00Z" or "2021-03-28T03:00:00+03:00") then the data's timezone is used instead of the dataTimezone option.
When using timezones, the exclusiveEndDates option is also turned on by default.
When using anything other than the default, a timezone plugin must be also passed to the component.
Possible values are:
  • 'local' - Uses the systems local timezone
  • 'utc' - Displays data in UTC (Universal Coordinated Time)
  • Timezone name - The timezone name from the IANA time zone database ex. "America/New_York"
defaultSelection Date, String, moment, Array, null undefined

Default selection which appears on the picker. The provided value will not be set as picker value, it's only a pre-selection.

If not provided, the default selection will be the current date and/or time.

If null is passed, in case of the calendar control there will be no selected value, in case of scroller controls the current date and time will still be displayed on the selected line, as an empty value cannot be displayed on the scroller.

defaultValue Date, String, moment, Array undefined Default value of the component in case of uncontrolled usage. For specifying a default selection, without the value being set, use the defaultSelection option.
disabled Boolean false Initial disabled state of the component.
display String undefined Controls the positioning of the component. Possible options:
  • 'center' - The component appears as a popup at the center of the viewport.
  • 'inline' - If called on div element, the component is placed inside the div (overwriting existing content), otherwise is placed after the original element.
  • 'anchored' - The component appears positioned to the element defined by the anchor option. By default the anchor is the original element.
  • 'top' - The component appears docked to the top of the viewport.
  • 'bottom' - The component appears docked to the bottom of the viewport.

The default display mode depends on the theme, it defaults to 'bottom' for the iOS theme and to 'center' for all other themes.

In desktop mode (when the touchUi option is set to false) the default display mode is 'anchored'.

displayTimezone String 'local' Specifies the timezone of the selection. While the selection happens in the displayTimezone, the selected values will be converted to the dataTimezone before they are returned.
When using timezones, the exclusiveEndDates option is also turned on by default.
When using anything other than the default ('local'), a timezone plugin must be also passed to the component.
Possible values are:
  • 'local' - Default. Uses the systems local timezone
  • 'utc' - Displays data in UTC (Universal Coordinated Time)
  • Timezone name - The timezone name from the IANA time zone database ex. "America/New_York"
endInput String, HTMLElement, Mobiscroll Input or IonInput undefined Sets the Input for the end date. When using the datepicker to select a range, it can be used with one, two or no inputs. When an endInput is passed to the datepicker, it will put the range end part of the selection to that input. Similarly the input for the begin part can be specified by the startInput option.
exclusiveEndDates Boolean undefined If true, the Datepicker will work in exclusive end dates mode, meaning that the last moment of the range (event, invalid, colors, etc.) is not part of the range.

For example, when selecting a date range without the time part, selecting '2021-07-20' for the range end will return '2021-07-21' instead. Because the range ends on the 21st, not including the 21st.
When using timezones the exclusiveEndDates option defaults to true.
firstSelectDay Number firstDay

Sets the first day of the selection, when preset-range selection is used. It takes a number representing the day of the week. Ex. Sunday is 0, Monday is 1, etc.

When not set, it defaults to the first day of the week, which depends on the localization used.

The length of the selection can be controlled with the selectSize option.

focusOnClose Boolean, String, HTMLElement true Element to focus after the popup is closed. If undefined, the original element will be focused. If false, no focusing will occur.
focusTrap Boolean true If not in inline mode, focus won't be allowed to leave the popup.
headerText Boolean, String false Specifies a custom string which appears in the popup header.
If the string contains the '{value}' substring, it is replaced with the formatted value of the datepicker.
If it's set to false, the header is hidden.
height Number, String undefined Sets the height of the component.
inputComponent Function, String undefined

The input component to render if the picker is modal (the display option is not set to 'inline').

The following values are supported:

  • 'input' - renders a standard HTML input.
  • IonInput - renders an IonInput in case of Ionic React.

If not specified, a mobiscroll Input will be rendered.

Props can be specified using the inputProps option.

inputProps Object undefined Props for the rendered input, specified by the inputComponent option.
inputStyle String 'underline' Defines the input rendering mode. By default the input has the underline styling. Possible values:
  • 'underline'
  • 'box'
  • 'outline'
inputTyping Boolean true Allow the typing into the input field in desktop mode.
inRangeInvalid Boolean false

In case of range selection, determines if the invalid dates are allowed between the start and the end date.

When inRangeInvalid is set to false, the end selection will be limited to the next invalid date from the selected start date.

When designing a booking system, a possible solution for already booked dates is to set those dates to invalid.
When considering "check-in" and "check-out" selections with the datepicker, in some cases it is desireable to be able to check out on dates that already have a check-in. In this case, those dates would be disabled. Using the rangeEndInvalid option it can be allowed that the first invalid day after the start date can be selected as end date.

invalid Array undefined An array containing the invalid values.

Can contain dates (Javascript Date objects, ISO 8601 strings, or moment objects), or objects with the following properties:

In certain cases it might be more convinient to specify the valid values instead of the invalid ones. In this case use the valid option instead.

  • start: Date, String, Object - Start of the invalid range.
  • end: Date, String, Object - End of the invalid range.
  • recurring: String, Object - Recurrence rule for recurring invalid ranges.
  • recurringException: String, Object, Array - Recurrence exception for recurring invalids.
  • recurringExceptionRule: String, Object - Recurrence exception rule for recurring invalids.
  • cssClass String - Specifies the custom CSS class name. This property is only applicable in the case of the scheduler and timeline view.
Example
invalid: [
    // Passing exact dates and times
    new Date(2021, 1, 7), // Date object
    '2021-10-15T12:00', // ISO 8601 string
    moment("2020-12-25"), // moment object

    // Passing invalid ranges
    { 
      // ISO 8601 strings
      start: '2021-10-15T12:00',
      end: '2021-10-18T13:00', 
      title: 'Company 10th anniversary',
    },
    {
      // Date objects
      allDay: true,
      start: new Date(2021, 2, 7),
      end: new Date(2021, 2, 9),
      title: 'Conference for the whole team',
    },
    {
      // Time range with recurrence
      start: '13:00',
      end: '12:00',
      recurring: { repeat: 'weekly', weekDays: 'MO,TU,WE,TH,FR' },
      title: 'Lunch break',
    },
    {
      // Disable weekends
      recurring: {
          repeat: 'weekly',
          weekDays: 'SA,SU'
      }
    }
];
isOpen Boolean undefined Specifies wether the popup is opened or not. Use it together with the onClose event, by setting it to false when the popup closes.
itemHeight Number 40 Height in pixels of one item on the wheel. The default value depends on the theme:

iOS: 34
Material: 40
Windows: 44
labels Array undefined Specify labels for calendar days. A label object can have the following properties:
  • date Date, String, Object - Date of the calendar label.
  • start Date, String, Object - Start date of the calendar label.
  • end Date, String, Object - End date of the calendar label.
  • color String - The color of the label, can be any valid CSS color ('red', '#ff0000', 'rgb(255,0,0)', etc.).
  • text String - The text of the label.
  • recurring: String, Object - Recurrence rule for recurring labels.
  • recurringException: String, Object, Array - Recurrence exception for recurring labels.
  • recurringExceptionRule: String, Object - Recurrence exception rule for recurring labels.
  • cellCssClass: String - CSS class for the day cell. This property is only applicable in the case of the calendar view.
The dates can be specified as Javascript Date objects, ISO 8601 strings, or moment objects.
The labels can be combined with the colors option.
Example
labels: [{
  start: new Date(2020, 2, 23),
  end: new Date(2020, 2, 24),
  text: 'Conference',
  color: 'red'
}, {
  text: 'Christmas',
  recurring: { repeat: 'yearly', month: 12, day: 24 }
}]
labelStyle String undefined Defines the position of the label. The default label style depends on the theme option. With the 'ios' theme the inputs have inline labels, with 'mobiscroll', 'material' and 'windows' themes the default label position is stacked. Possible values:
  • 'stacked'
  • 'inline'
  • 'floating'
marked Array undefined Mark certain dates on the calendar. Must be an array containing dates (Javascript Date objects, ISO 8601 strings, or moment objects), or objects with the following properties:
  • date Date, String, Object - Date of the day to be marked.
  • start Date, String, Object - Start date of the days to be marked.
  • end Date, String, Object - End date of the days to be marked.
  • color String - The color of the mark, can be any valid CSS color ('red', '#ff0000', 'rgb(255,0,0)', etc.).
  • recurring: String, Object - Recurrence rule for recurring marked days.
  • recurringException: String, Object, Array - Recurrence exception for marked days.
  • recurringExceptionRule: String, Object - Recurrence exception rule for marked days.
  • cellCssClass: String - CSS class for the day cell. This property is only applicable in the case of the calendar view.
  • markCssClass: String - CSS class for the mark.
The dates can be specified as Javascript Date objects, ISO 8601 strings, or moment objects.
The marked option can be combined with the colors option.
Example
marked: [
  new Date(2020, 2, 15),
  new Date(2020, 2, 22),
  {
    start: new Date(2020, 2, 23),
    end: new Date(2020, 2, 24),
    color: 'red'
  },
  {
    color: 'green',
    recurring: { repeat: 'yearly', month: 12, day: 24 }
  }
]
max Date, String, Object undefined Maximum value that can be selected.
maxRange Number undefined

It sets the maximum range that can be selected. When selecting a date without the time part, it sets the maximum number of days the selected range can contain. When there is a time part in the selection, it sets the maximum range in milliseconds.

maxTime string, Date or Moment object undefined

It sets the maximum time that is selectable on the time or the timegrid control.

When there is a date part of the selection, the maximum is applied to each day. For example

maxTime: '18:00'
will limit the time part of the selection to at most 18 o'clock each day.

In contrast to the max option, which will limit the date part of the selection as well. For example:
max: '2021-08-22T18:00
will limit the selection to August 22nd 18 o'clock, but will allow selection of times past 18 o'clock on dates before Aug. 22nd.

This option can't be used with the ['datetime'] control.

maxWheelWidth Number, Array undefined Maximum width of the scroller wheels in pixels.
If number, it is applied to all wheels, if an array, it is applied to each wheel separately.
maxWidth Number, String 600 Sets the maximum width of the component.
min Date, String, Object undefined Minimum value that can be selected.
minRange Number undefined

It sets the minimum range that can be selected. When selecting a date range without the time part, it sets the minimum number of days the selected range can contain. When there is a time part in the selection, it sets the minimum range in milliseconds.

minTime string, Date or Moment object undefined

It sets the minimum time that is selectable on the time or the timegrid control.

When there is a date part of the selection, the minimum is applied to each day. For example

minTime: '08:00'
will limit the time part of the selection to at least 8 o'clock each day.

In contrast to the min option, which will limit the date part of the selection as well. For example:
min: '2021-08-22T08:00
will limit the selection to August 22nd 8 o'clock, but will allow selection of times earlier than 8 o'clock on dates after Aug. 22nd.

This option can't be used with the 'datetime' control.

minWheelWidth Number, Array 80 Minimum width of the scroller wheels in pixels.
If number, it is applied to all wheels, if an array, it is applied to each wheel separately.
The default value depends on the theme:

iOS: 55
Material: 80
Windows Phone: 88
minWidth Number, String undefined Sets the maximum width of the component.
moment object undefined Reference to the Moment.js library.
When using Moment objects as return values, this setting should be passed the reference to the Moment.js library.
Check out our example on how to pass moment to the datepicker !
multiple Boolean false If true, multiple selection will be enabled.
pages Number, String 1 Number of calendar pages (month or week) to display. If 'auto', the displayed number of pages will be decided based on the viewport size.
rangeEndInvalid Boolean false

When true, it enables the end date to be selected on the first invalid date that comes after the selected start date.

For example, when designing a booking system, a possible solution for already booked dates is to set those dates to invalid.
When considering "check-in" and "check-out" selections with the datepicker, in some cases it is desireable to be able to check out on dates that already have a check-in. In this example those dates would be disabled. With the rangeEndInvalid option it can be enabled, so the selection's end can be on the same day the first invalid is.

When the inRangeInvalid option is set to true (default), this option is ignored, so be sure to turn that off too if you want to use this one.
rangeHighlight Boolean true

When selecting a range on the calendar control, it is optional to highlight the dates between the start and end date.

By default, the dates are highlighted between the start and end values. When the highlight is turned off, only the start and end dates are shown as selected on the calendar.

On desktop devices where a cursor is available, hovering the calendar days also help to visualize the selecting range. The hover styling is also turned off, when the range is not highlighted.

refDate Date, String, Object 1970/01/01 Specifies the reference date of the component, which represents when to start to calculate the view you want to display. For example, if you want to display 2 months from the current month, you must specify the first day of the current month as the reference date. Then you can use the calendarSize option to show 2 months.
renderCalendarHeader Function undefined

Use this option to customize the header of the Datepicker. It takes a function that should return the desired markup. In the returned markup, you can use custom html as well as the built in header components of the calendar.

Check out the customizing the header section for a more detailed description on built in components.

Example with built in components
const myCustomHeader = () => {
    return <>
        <CalendarPrev />
        <CalendarNext />
    </>
}
renderDay Function undefined

You can use the renderDay option to customize the day cells of the Datepicker. It takes a function that should return the desired markup. The Datepicker will take care of the positioning, but everything else (like background color, hover effect, etc.) is left to you.

If you are looking to customize only the content and don't want to bother with the styling of the event, you can use the renderDayContent option.

The render function will receive an object as parameter. This data can be used to show day specific things on the Datepicker. The object passed to the function has the following properties:

  • date: Date object - The specific date as a Date object.
  • selected: Boolean - True if the date is selected. (In case of calendar view)
  • events: Array - The list of events of the day.
Example
const myCustomDay = (day: any) => {
    const date = day.date;

    return <>
        <div>{formatDate('DDDD', date)}</div>
        <p>{formatDate('MMMM DD', date)}</p>
    </>;
}
renderDayContent Function undefined

You can use the renderDayContent option to customize the day content of the Datepicker. It takes a function that should return the desired markup. The Datepicker will take care of styling and you can focus on what you show beside the day number a.k.a the content.

If you are looking to fully customize the day (ex. add custom hover effects) you will need to use the renderDay option. In that case you will only get the positioning done by the Datepicker and everything else is up to you.

The render function will receive an object as parameter. This data can be used to show day specific things on the Datepicker. The object passed to the template has the following properties:

  • date: Date object - The specific date as a Date object.
  • selected: Boolean - True if the date is selected.
  • events: Array - The list of events of the day.
Example
const myCustomDay = (day: any) => {
    const date = day.date;

    return <>
        <div>{formatDate('DDDD', date)}</div>
        <p>{formatDate('MMMM DD', date)}</p>
    </>;
}
responsive Object undefined Specify different settings for different container widths, in a form of an object, where the keys are the name of the breakpoints, and the values are objects containing the settings for the given breakpoint.
The available width is queried from the container element of the component and not the browsers viewport like in css media queries
There are five predefined breakpoints:
  • xsmall - min-width: 0px
  • small - min-width: 576px
  • medium - min-width: 768px
  • large - min-width: 992px
  • xlarge - min-width: 1200px
Custom breakpoints can be defined by passing an object containing the breakpoint property specifying the min-width in pixels. Example:
responsive: {
    small: {
        display: 'bottom'
    },
    custom: { // Custom breakpoint
        breakpoint: 600,
        display: 'center'
    },
    large: {
        display: 'anchored'
    }
}
returnFormat String 'jsdate' Specifies the format in which the selected date(s) is returned in the onChange event.
Possible values:
  • 'jsdate' - Javascript date object
  • 'iso8601' - ISO 8601 date string.
  • 'locale' - Formatted date string based on the lang setting, or the dateFormat and timeFormat settings, if they are specified.
  • 'moment' - moment object. Ensure that moment.js is loaded.
When using Moment.js, the reference to the moment library must be passed to the component via the moment option. Check out our example on how to pass moment to the datepicker !
When using a timezone plugin, the returned values are always in 'iso8601' format and this option is not taken into account.
rows Number 3 Number of visible rows on the wheel. The default value depends on the theme:

iOS: 5
Material: 3
Windows: 6
scrollLock Boolean true Disables page scrolling on touchmove (if not in inline mode, and popup height is less than window height).
select String 'date'

In terms of value selection, the datepicker can be used to select a single date/time or multiple dates/times, as well as a date range or a time range. It is also possible to select a week or a part of the week as a range, called preset-range.

The select setting defines if the picker is used for selecting independent dates or a range.

Possible values are:

  • 'date' - it is used for single of multiple date/time selection
  • 'range' - it is used for date range or time range selection
  • 'preset-range' - it is used for a week range selection

selectCounter Boolean false If true and multiple selection is enabled, the number of selected items will be displayed in the header.
selectMax Number undefined The maximum number of selected items in case of multiple selection.
selectMultiple Boolean false If true, multiple selection will be enabled.
selectSize Number 7

Sets the length of the selection in days when the preset-range selection is used.

It defaults to the whole week (7 days).

The selection will start depending on the firstSelectDay option and will have the number of days specified by the selectSize.

showArrow Boolean true Show or hide the popup arrow, when display mode is 'anchored'.
showInput Boolean true If true, it will render an input field for the component.
showOnClick Boolean true Opens the component on element click/tap.
showOnFocus Boolean false - on desktop true - on mobile Pops up the component on element focus.
showOuterDays Boolean true

Show or hide days from previous and next months.

Hiding outer days only works in case of month view, and not supported for week view.

Outer days are automatically hidden if calendarScroll is set to 'vertical'.

showOverlay Boolean true Show or hide overlay.
showRangeLabels Boolean true

By default when selecting a range, a start and end label is shown on the Datepicker. These labels indicate which part of the range are we selecting (start or end). The labels can also be used to switch the active selection from start to end or vice versa.

The showRangeLabels option can be used to show or hide the labels.

The start label text and end label text as well as the start value placeholder and end value placeholder can be localized and/or customized.

showWeekNumbers Boolean false Show week numbers on the calendar view. Enumeration starts with the first week of the year.
startInput String, HTMLElement, Mobiscroll Input or IonInput undefined Sets the Input for the start date. When using the datepicker to select a range, it can be used with one, two or no inputs. When a startInput is passed to the datepicker, it will put the range beginning part of the selection to that input. Similarly the input for the end part can be specified by the endInput option.
stepHour Number 1 Step for the hours scroll wheel. Also, sets the hours step for the timegrid.
stepMinute Number 1 Step for the minutes scroll wheel. Also, sets the minutes step for the timegrid.
stepSecond Number 1 Step for the seconds scroll wheel. Also, sets the seconds step for the timegrid.
tabs Boolean undefined Show / hide tabs for calendar, date and time controls. If undefined, it is automatically decided to show or hide tabs based on available space. If only one control is passed, tabs are always hidden.
tagInput Boolean false If true and multiple selection is enabled, it will display multiple values as "chips/tags".
theme String undefined

Sets the visual appearance of the component.

If it is 'auto' or undefined, the theme will automatically be chosen based on the platform. If custom themes are also present, they will take precedence over the built in themes, e.g. if there's an iOS based custom theme, it will be chosen on the iOS platform instead of the default iOS theme.

Supplied themes:
  • 'ios' - iOS theme
  • 'material' - Material theme
  • 'windows' - Windows theme
It's possible to modify theme colors or create custom themes.
Make sure that the theme you set is included in the downloaded package.
themeVariant String undefined

Controls which variant of the theme will be used (light or dark).

Possible values:
  • 'light' - Use the light variant of the theme.
  • 'dark' - Use the dark variant of the theme.
  • 'auto' or undefined - Detect the preferred system theme on devices where this is supported.

To use the option with custom themes, make sure to create two custom themes, where the dark version has the same name as the light one, suffixed with '-dark', e.g.: 'my-theme' and 'my-theme-dark'.

timezonePlugin Object undefined

Specifies the timezone plugin, which can handle the timezone conversions.

By default the Datepicker uses the local timezone of the browser for value selection. If you want to select a date-time in a different timezone, you will need an external library to handle the timezone conversions. There are two supported libraries: moment-timezone and luxon.
Read our guide on how to set up timezones in your app.

You can specify either the dataTimezone or the displayTimezone or both.

Depending on which externa library you use you can pass either the

  • momentTimezone
  • luxonTimezone
objects to the timezonePlugin option. These objects can be imported from the mobiscroll bundle:
import { momentTimezone, luxonTimezone } from '@mobiscroll/react';
Example
<Datepicker timezonePlugin={momentTimezone} dataTimezone="utc" displayTimezone="America/New_York"/>

touchUi Boolean, String 'auto'

Use true to render a touch optimized user interface, or false for a user interface optimized for pointer devices (mouse, touchpad).

Can be used with the responsive option to change the user interface based on viewport width.

If set to 'auto', the touch UI will be automatically enabled based on the platform.

valid Array undefined

An array containing the valid values. Use it when it's more convinient to specify valid values instead of the invalid ones. If specified, everything else is considered to be invalid, and the invalid option will be ignored.

Can contain dates (Javascript Date objects, ISO 8601 strings, or moment objects), or objects with the following properties:

  • allDay: Boolean - If true the specified date will cover the whole day.
  • start: Date, String, Object - Start of the valid range.
  • end: Date, String, Object - End of the valid range.
  • recurring: String, Object - Recurrence rule for recurring valid ranges.
  • recurringException: String, Object, Array - Recurrence exception for recurring valids.
  • recurringExceptionRule: String, Object - Recurrence exception rule for recurring valids.
Example
valid: [
    // Passing exact dates and times
    new Date(2022, 1, 7), // Date object
    '2021-10-15T12:00', // ISO 8601 string
    moment("2022-12-25"), // moment object

    // Passing valid ranges
    { 
      // ISO 8601 strings
      start: '2021-10-15T12:00',
      end: '2021-10-18T13:00',
    },
    {
      // Date objects
      allDay: true,
      start: new Date(2021, 2, 7),
      end: new Date(2021, 2, 9),
    },
    {
      // Time range with recurrence
      start: '09:00',
      end: '20:00',
      recurring: {
        repeat: 'weekly',
        weekDays: 'MO,TU,WE,TH,FR',
        interval: 1
      }
    }
];
weeks Number 1 Number of weeks to display if calendarType is set to 'week'.
Deprecated, use the calendarSize option instead.
wheelWidth Number, Array undefined Width of the scroller wheels, in pixels. Wheel content will be truncated, if it exceeds the width.
If number, it is applied to all wheels, if an array, it is applied to each wheel separately.
width Number, String undefined Sets the width of the popup container. This will take no effect in inline display mode.

Setting options dynamically

To make an option dynamic, you can pass a variable as option value. Whenever the value of the variable changes, the component will be re-rendered.

const App = () => {
        
  const [myTheme, setMyTheme] = useState('ios');

  const changeTheme = useCallback(() => {
    // Changes the theme to Material
    setMyTheme('material');
  }, []);

  return <div>
    <Datepicker theme={myTheme} />
    <button onClick={changeTheme}>Change theme</button>
  </div>;
};
For performance reasons on re-render we compare prop values by reference. This means, that in case of options, which accept complex data structures, like arrays or objects, changes made inside the array or object won't be detected. To ensure the change is detected, always pass a new array or object reference.

Events

Name Description
onActiveDateChange(event, inst) In range selection mode, the onActiveDateChange event is triggered when the active date changes from start to end or vice versa.

Parameters

  • event: Object - The event object has the following properties:
    • active: String - The activated part of the range: either 'start' or 'end'.
  • inst: Object - The instance object of the datepicker.
onCancel(event, inst) Allows you to define your own event when cancel is pressed.

Parameters

  • event: Object - The event object has the following properties:
    • valueText: String - The selected value as text.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onCancel={function (event, inst) {
    }}
/>
onCellClick(event, inst) Triggered when a cell is clicked on the calendar .

Parameters

  • event: Object - The event object has the following properties:
    • date: Date - The date of the clicked cell.
    • domEvent: Event The DOM event of the click.
    • selected: Boolean - Specifies if the day is currently selected or not (before it was clicked).
    • target: HTMLElement - The DOM element of the clicked cell.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onCellClick={function (event, inst) {
    }}
/>
onChange(event, inst) Triggered when the value is changed.

Parameters

  • event: Object - The event object has the following properties:
    • value - The selected value
    • valueText: String - The selected value as text (if any).
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onChange={function (event, inst) {
    }}
/>
onClose(event, inst) Triggered when the component is closed.

Parameters

  • event: Object - The event object has the following properties:
    • valueText: String - The selected value as text.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onClose={function (event, inst) {
    }}
/>
onDestroy(event, inst) Triggered when the component is destroyed.

Parameters

  • event: Object - The event object.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onDestroy={function (event, inst) {
    }}
/>
onInit(event, inst) Triggered when the component is initialized.

Parameters

  • event: Object - The event object.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onInit={function (event, inst) {
    }}
/>
onLabelClick(event, inst) Triggered when a label on the calendar is clicked.

Parameters

  • event: Object - The event object has the following properties:
    • date: Date - The date of the day on which the label was clicked.
    • domEvent: Event - The DOM event of the click.
    • label: Object - The original object of the label which was clicked, undefined in case of the "more" label.
    • labels: Array - An array containing each label object for the given day.
    • target: HTMLElement - The DOM element of the label.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onLabelClick={function (event, inst) {
    }}
/>
onOpen(event, inst) Triggered when the component is opened.

Parameters

  • event: Object - The event object has the following properties:
    • target: Object - The DOM element containing the generated html.
    • valueText: String - The selected value as text.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onOpen={function (event, inst) {
    }}
/>
onPageChange(event, inst) Triggered when the calendar page is changed (month or week, with buttons or swipe).

Parameters

  • event: Object - The event object has the following property:
    • firstDay: Date - The first day of the displayed page.
    • lastDay: Date - The last day of the displayed page.
    • month: Date - The first day of the visible month in case of month view.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onPageChange={function (event, inst) {
    }}
/>
onPageLoaded(event, inst) Triggered when the calendar page is changed (month or week, with buttons or swipe) and the animation has finished.

Parameters

  • event: Object - The event object has the following property:
    • firstDay: Date - The first day of the displayed page.
    • lastDay: Date - The last day of the displayed page.
    • month: Date - The first day of the visible month in case of month view.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onPageLoaded={function (event, inst) {
    }}
/>
onPageLoading(event, inst) Triggered before the markup of a calendar page (month or week) is starting to render.

Parameters

  • event: Object - The event object has the following property:
    • firstDay: Date - The first day of the displayed page.
    • lastDay: Date - The last day of the displayed page.
    • month: Date - The first day of the visible month in case of month view.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onPageLoading={function (event, inst) {
    }}
/>
onPosition(event, inst) Triggered when the component is positioned (on initial show and resize / orientation change).
Useful if dimensions needs to be modified before the positioning happens, e.g. set a custom width or height. Custom positioning can also be implemented here, in this case, returning false from the handler function will prevent the built in positioning.

Parameters

  • event: Object - The event object has the following properties:
    • target: Object - The DOM element containing the generated html.
    • windowWidth: Number - The window width.
    • windowHeight: Number - The window height.
  • inst: Object - The instance object of the datepicker.

Example

<mobiscroll.Datepicker
    onPosition={function (event, inst) {
    }}
/>
onTempChange(event, inst) Triggered when the temporary value is changed.

Parameters

  • event: Object - The event object has the following properties:
    • value: String, Date, Moment.js Object or Array of String, Date, Moment.js object - The selected value.
  • inst: Object - The instance object of the datepicker.

Methods

Name Description
close() Closes the component.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.close();
getTempVal()

Returns the temporary value that's selected on the picker.

Depending on how the picker is displayed, the selection might be in a temporary state that hasn't been set yet. This temporary value can be aquired calling the getTempVal method on the picker instance.

The value that has been set to the model can be aquired using the getVal() method.

The getTempVal and getVal methods are usually for advanced use-cases, when the built in options and the state management tools of React are not sufficien to work with.

Returns: String, Date, Moment.js Object or Array of String, Date or Moment.js Object

The return value type depends on the returnFormat and the select option.

getVal() Returns the selected value of the picker, that has been set to the model as well.

Depending on how the picker is displayed, the selection might be in a temporary state that hasn't been set yet. This temporary value can be aquired calling the getTempVal method on the picker instance.

Returns: String, Date, Moment.js Object or Array of String, Date or Moment.js Object

The return value type depends on the returnFormat and the select option.

The getTempVal and getVal methods are usually for advanced use-cases, when the built in options and the state management tools of React are not sufficien to work with.
isVisible() Returns a boolean indicating whether the component is visible or not.

Returns: Boolean

  • True if the component is visible, false if it's not.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.isVisible();
navigate(date) Display a specific month on the calendar without setting the date.

Parameters

  • date: Date, String, Object - Date to navigate to. Can be a Date object, ISO8601 date string, or moment object.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.navigate(new Date(2016, 1, 1));
open() Opens the component.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.open();
position() Recalculates the position of the component (if not inline).

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.position();
setActiveDate(active) Sets which date is currently selected (start or end). If the picker is visible, it will also highlight the respective date.

Parameters

  • active: String - Currently selected date. It can be 'start' or 'end'.

Example

Methods can be called on an instance. For more details see calling methods
mobiscrollInstance.setActiveDate('start');
setTempVal(value)

Sets the temporary value that's selected on the picker.

Depending on how the picker is displayed, the selection shown might be just a temporary value until the users hit the "Set" button to commit the selection. This temporary value can be adjusted calling the setTempVal method on the picker instance.

To get the current temporary value, check out the getTempVal instance method.

The setTempVal and setVal methods are usually for advanced use-cases, when the built in options and the state management tools of React are not sufficien to work with.

Parameters

  • value: String, Date, Moment.js Object or Array of String, Date, Moment.js Object - Can be a date string in the specified date format, a Date object, a Moment.js Object or an Array of these.

The type of the value parameter depends on the returnFormat and the select options.

setVal(value) Sets the picker value and also writes it to the model.

Depending on how the picker is displayed, the selection shown might be just a temporary value until the users hit the "Set" button to commit the selection. This temporary value can be adjusted calling the setTempVal method on the picker instance.

To get the current selected value, check out the getVal instance method.

Parameters

  • value: String, Date, Moment.js Object or Array of String, Date or Moment.js Object - the value to set to the picker

The value type should be choosen depending on the returnFormat and the select option.
In case of the range selection, the value should be an array with two values, the first being the start, and the second being the end.

The setTempVal and setVal methods are usually for advanced use-cases, when the built in options and the state management tools of React are not sufficien to work with.

Localization

Name Type Default value Description
amText String 'am' Text for AM.
cancelText String 'Cancel' Text for Cancel button.
dateFormat String 'MM/DD/YYYY' The format for parsed and displayed dates.
  • M - month of year (no leading zero)
  • MM - month of year (two digit)
  • MMM - month name short
  • MMMM - month name long
  • D - day of month (no leading zero)
  • DD - day of month (two digit)
  • DDD - day of week (short)
  • DDDD - day of week (long)
  • YY - year (two digit)
  • YYYY - year (four digit)
  • '...' - literal text
  • '' - single quote
  • anything else - literal text
dateWheels String undefined Display order and formating for month/day/year wheels. Characters have the same meaning as in the dateFormat option. The options also controls if a specific wheel should appear or not, e.g. use 'mmyy' to display month and year wheels only, 'mmD ddy' to display both day of week and date on the day wheel.

If not specified, the order of the wheels will be taken from the dateFormat option, and the formating will be defined by the theme

Starting for 3.0.0-beta5 an experimental feature was introduced to display the whole date on one wheel. To activate this mode, the format of the date should be specified between | charchters:

dateWheels: '|D M d|' // Will produce 'Sun Sep 9'
            
dayNames Array ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] The list of long day names, starting from Sunday, for use as requested via the dateFormat setting.
dayNamesMin Array ['S', 'M', 'T', 'W', 'T', 'F', 'S'] The list of minimal day names, starting from Sunday, for use as requested via the dateFormat setting.
dayNamesShort Array ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] The list of abbreviated day names, starting from Sunday, for use as requested via the dateFormat setting.
daySuffix String undefined Additional string to display after the day on the wheel.
firstDay Number 0 Set the first day of the week: Sunday is 0, Monday is 1, etc.

When preset-range selection is used the range start day can be specified with the firstSelectDay option.

headerText Boolean, String '{value}' Specifies a custom string which appears in the popup header.
If the string contains '{value}' substring, it is replaced with the formatted value of the datepicker.
If it's set to false, the header is hidden.
locale Object undefined Sets the language of the component. The locale option is an object containing all the translations for a given language. Mobiscroll supports a number of languages listed below. If a language is missing from the list, it can also be provided by the user. Here's a guide on how to write language modules.
Supported languages:
  • Arabic: localeAr, 'ar'
  • Bulgarian: localeBg, 'bg'
  • Catalan: localeCa, 'ca'
  • Czech: localeCs, 'cs'
  • Chinese: localeZh, 'zh'
  • Croatian: localeHr, 'hr'
  • Danish: localeDa, 'da'
  • Dutch: localeNl, 'nl'
  • English: localeEn or undefined, 'en'
  • English (UK): localeEnGB, 'en-GB'
  • Farsi: localeFa, 'fa'
  • German: localeDe, 'de'
  • Greek: localeEl, 'el'
  • Spanish: localeEs, 'es'
  • Finnish: localeFi, 'fi'
  • French: localeFr, 'fr'
  • Hebrew: localeHe, 'he'
  • Hindi: localeHi, 'hi'
  • Hungarian: localeHu, 'hu'
  • Italian: localeIt, 'it'
  • Japanese: localeJa, 'ja'
  • Korean: localeKo, 'ko'
  • Lithuanian: localeLt, 'lt'
  • Norwegian: localeNo, 'no'
  • Polish: localePl, 'pl'
  • Portuguese (Brazilian): localePtBR, 'pt-BR'
  • Portuguese (European): localePtPT, 'pt-PT'
  • Romanian: localeRo, 'ro'
  • Russian: localeRu, 'ru'
  • Russian (UA): localeRuUA, 'ru-UA'
  • Slovak: localeSk, 'sk'
  • Serbian: localeSr, 'sr'
  • Swedish:localeSv, 'sv'
  • Thai: localeTh, 'th'
  • Turkish: localeTr, 'tr'
  • Ukrainian: localeUa, 'ua'
  • Vietnamese: localeVi, 'vi'
import { Eventcalendar, localeDe } from '@mobiscroll/react';

export function MyComponent() {
  return <Eventcalendar locale={localeDe} />;
}

In some cases it's more convenient to set the locale using the language code string. You can do that by using the locale object, which contains all translations by language codes as keys.

The locale object is not tree-shakeable, meaning that all translations present in the object will end up in the application bundle, whether it's being used or not.
import { Eventcalendar, locale } from '@mobiscroll/react';

export function MyComponent() {
  return <Eventcalendar locale={locale['de']} />;
}
monthNames Array ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] The list of full month names, for use as requested via the dateFormat setting.
monthNamesShort Array ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] The list of abbreviated month names, for use as requested via the dateFormat setting.
monthSuffix String undefined Additional string to display after the month on the wheel.
moreEventsPluralText String undefined Text for the "more" label on the calendar, when there's not enough space to display all the labels for the day, and there are more than one extra labels. The {count} inside the string will be replaced with the number of extra labels. When not specified, the moreEventsText setting is used for both plural and singular form.
moreEventsText String '{count} more' Text for the "more" label on the calendar, when there's not enough space to display all the labels for the day. The {count} inside the string will be replaced with the number of extra labels. Use the moreEventsPluralText as well, if the plural form is different.
nextPageText String 'Next page' Text for the next page button in the calendar header, used as accessibility label.
nowText String 'Now' Label for the 'Now' button.
pmText String 'pm' Text for PM.
prevPageText String 'Previous page' Text for the previous page button in the calendar header, used as accessibility label.
rangeEndHelp String 'Please select' When selecting a range, it specifies the placeholder text for the end value under the end label.
rangeEndLabel String 'End' When selecting a range, it specifies the text of the end label.
rangeStartHelp String 'Please select' When selecting a range, it specifies the placeholder text for the start value under the start label.
rangeStartLabel String 'Start' When selecting a range, it specifies the text of the start label.
rtl Boolean false Right to left display.
selectedPluralText String '{count} selected' Specifies the plural form of the amount of selected items according to the rules of particular language. The '{count}' substring will be replaced with the number of selected items.
selectedText String '{count} selected' Specifies the amount of selected items according to the rules of particular language. The '{count}' substring will be replaced with the number of selected items.
setText String 'Set' Text for Set button.
timeFormat String 'hh:mm A' The format for parsed and displayed dates
  • h - 12 hour format (no leading zero)
  • hh - 12 hour format (leading zero)
  • H - 24 hour format (no leading zero)
  • HH - 24 hour format (leading zero)
  • m - minutes (no leading zero)
  • mm - minutes (leading zero)
  • s - seconds (no leading zero)
  • ss - seconds (leading zero)
  • a - lowercase am/pm
  • A - uppercase AM/PM
  • '...' - literal text
  • '' - single quote
  • anything else - literal text
timeWheels String undefined Display order and formating of the time wheels on the datepicker. Characters have the same meaning as in the timeFormat option.

If not specified, the order of the wheels will be taken from the timeFormat option, and the formating will be defined by the theme

Starting for 3.0.0-beta5 an experimental feature was introduced to display the whole time on one wheel. To activate this mode, the format of the time should be specified between | charchters:
timeWheels: '|h:mm A|' // Will produce '9:12 AM' 
yearSuffix String undefined Additional string to display after the year on the wheel.

Customizing the appearance

While the provided pre-built themes are enough in many use cases, most of the times on top of adapting to a specific platform, you'd also like to match a brand or color scheme. Mobiscroll provides various ways to achieve this:

Override the Sass Color Variables

A convenient way to customize the colors of the Mobiscroll components is to override the Sass color variables.

Let's say your branding uses a nice red accent color, and you'd like that color to appear on the Mobiscroll components as well, while still using platform specific themes (e.g. ios on iOS devices, material on Android devices, and mobiscroll on desktop). You can override the accent color for every theme:

$mbsc-ios-accent: #e61d2a;
$mbsc-material-accent: #e61d2a;
$mbsc-mobiscroll-accent: #e61d2a;

@import "~@mobiscroll/React/dist/css/mobiscroll.react.scss"
It's important that you override the variables BEFORE the scss file import, otherwise it won't make any difference.
Here's a complete guide on how to set up Mobiscroll with SASS support

You can also customize the colors on many levels:

  1. Theme specific variables (ex. $mbsc-material-background, $mbsc-ios-dark-text) are applied to all components in a theme. Complete list of variables here.
  2. Component specific global variables (ex. $mbsc-card-background-light, $mbsc-listview-text-dark) are applied to all themes for a specific component.
  3. Component and theme specific variables (ex. $mbsc-ios-dark-form-background, $mbsc-material-input-text) are applied to a specific theme and a specific component.

Tree Shaking for styles

Tree shaking is a term commonly used in web development and particularly in JavaScript for unused code removal. Since websites are served (mostly) over the network, loading times depend on content size, so minification and unused content elimination plays a major role in making webapps fluid.

For the JavaScript part, popular frameworks already have the treeshaking built in, so the components that are not used will be left out from the built project.

Eliminating unused styles

In case of the styles, leaving out the unused rules is not as straight forward.
The overarching idea is that CSS selectors match elements in the DOM, and those elements in the DOM come from all sorts of places: your static templates, dynamic templates based on server-side state, and of course, JavaScript, which can manipulate the DOM in any way at all, including pull things from APIs and third parties.

Sass variables to the rescue

The Mobiscroll Library comes with a modular SASS bundle, that can be configured which component styles and which themes to leave in and out for the compiled css file.

Every component and theme has a SASS variable that can be turned on or off. If the variable is falsy the styles that it needs will not be added to the bundle.

Example on configuring the styles
// include the ios theme
$mbsc-ios-theme: true;

// include the components:
$mbsc-datepicker: true;
$mbsc-eventcalendar: true;
        
@import "@mobiscroll/react/dist/css/mobiscroll.modular.scss"

In the above example the styles needed for the eventcalendar and datepicker will be included and only for the ios theme. All other components (like select or grid-layout) and all other themes will be left out from the bundle.

It's important that you override the variables BEFORE the scss file import, otherwise it won't make any difference.

Here's the complete list of the components and themes that can be used:

Some components use others internally, so it might happen that even though you don't want to include some styles, they will still end up in your bundle.
For example if you don't want to include the form components (input, button, segmented, etc...), but you are using the select component, the styles for the mobiscroll buttons, will still be in, because of the dependency.

Accessibility

Keyboard Support

The datepicker component can render different kinds of controls on the screen depending on the use-case. Each of these controls can be operated by keyboard.

When focusing the input component one can open the picker using the Space or Enter keys.

The Esc key acts as the cancel button and closes the picker.

The Tab and Shift + Tab keys can be used to navigate between the major parts of the datepicker:

Buttons can be activated using the Space key.

Calendar

When focusing the calendar control or the month and year navigation, the focus can be moved using the Left, Right, Up and Down arrow keys.

The focused day (or month or year depending on the selection) can be marked as selected with the Space key or the Enter key. The later also confirms the selection and closes the datepicker.

Date & Time

When using the date and time scrollers, the Tab and Shift + Tab keys can be used to move the focus between the rendered wheels. The Up and Down arrow keys are used to rotate the wheel and change the selected value.

The selection can be confirmed with the Enter key, which also closes the picker.

Timegrid

The selectable times can be navigated using the Tab and Shift + Tab keys. The focused item can be marked as selected with the Space key or the Enter key. The later also confirms the selection and closes the datepicker.