Add input mask to React DatePicker

DaRoGa picture DaRoGa · Aug 15, 2018 · Viewed 8k times · Source

I have had a google and cant seem to find what I am looking for.

I need a React Datepicker that allows the use of an input mask and the input mask stays in place as you override it number by number ie. dd/MM/yyyy or //____ turns to 01/0M/yyyy or 01/0_/____. Ideally the first option where it specifies which item goes in which field.

I have tried a few different components but failed.

The component I am currently using is react-datepicker however this doesnt seem to be able to do it. Any advice or workarounds would be appreciated.

Answer

Aleksandr Shevelev picture Aleksandr Shevelev · Aug 15, 2018

We had a similar problem while using react-datepicker library, for a masked input you can use customInput property as described in react-datepicker documenentation. As a masked input for datepicker we used an input created with react-text-mask library. So we got code like this as the result:

import React from "react";
import Calendar from "react-datepicker";
import MaskedTextInput from "react-text-mask";

const DatePicker = props => (
   <Calendar
     customInput={
       <MaskedTextInput
         type="text"
         mask={[/\d/, /\d/, ".", /\d/, /\d/, ".", /\d/, /\d/, /\d/, /\d/]}
       />
     }
   />
);

This results into datepicker with custom input with enforsed mask __.__.___, replacing /\d/ with exact values (as dots in example above) you will get a prefilled mask. For datepicker to correctly interact with user we also added onChange handler to masked input with date validation.