Skip to content

Instantly share code, notes, and snippets.

@blehr
Last active June 22, 2018 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blehr/24e963c0a0f3341ccc40b69c0402bc9f to your computer and use it in GitHub Desktop.
Save blehr/24e963c0a0f3341ccc40b69c0402bc9f to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import moment from 'moment';
// import { formatDateInputs } from '../../utils/helper_functions';
const formatDateInputs = (value) => {
let input = value || '';
input = input.replace(/\D/g, '');
input = input.substring(0, 8);
const size = input.length;
if (size < 3) {
return input;
}
if (size < 5) {
return `${input.substring(0, 2)}/${input.substring(2, 4)}`;
}
if (size < 9) {
return `${input.substring(0, 2)}/${input.substring(2, 4)}/${input.substring(4)}`;
}
};
class DatePickerCustomInput extends Component {
constructor(props) {
super(props);
this.state = {
stateValue: '',
};
}
componentWillMount() {
this.setState({ stateValue: formatDateInputs(this.props.value) });
}
componentWillReceiveProps(nextProps) {
if (nextProps.value) {
const newValue = formatDateInputs(nextProps.value);
this.setState({ stateValue: newValue });
}
}
handleRawChange = (e) => {
const date = e.target.value;
const newDate = formatDateInputs(date);
this.setState({ stateValue: newDate });
if (newDate.length === 10 && moment(newDate, 'MM/DD/YYYY').isValid) {
this.props.pickerOnChange(moment(newDate, 'MM/DD/YYYY').toISOString());
}
};
render() {
return (
<input
type="text"
value={this.state.stateValue === 'Invalid date' ? '' : this.state.stateValue}
onChange={this.handleRawChange}
onClick={this.props.onClick}
placeholder="MM/DD/YYYY"
onBlur={this.props.onBlur}
disabled={this.props.disabled}
/>
);
}
}
export default DatePickerCustomInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment