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.
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.
    import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import MaskedInput from 'react-maskedinput';
import moment from 'moment';
export default class DateField extends Component {
  constructor(props) {
    super(props);
    this.state = { value: '' }
  }
  updateDate(value) {
    let fieldValue = moment(value).isValid() ?
      moment(value).format('MM/DD/YYYY') :
      value;
    this.setState({ value: fieldValue })
  }
  render() {
    const { value } = this.state;
    return (
      <DatePicker
        value={value}
        onChange={value => this.updateDate(value)}          
        type="text"
        dateFormat="MM/DD/YYYY"
        customInput={
          <MaskedInput mask="11/11/1111" placeholder="mm/dd/yyyy" />
        }
      />
    );
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With