Last active
June 22, 2018 14:23
-
-
Save blehr/24e963c0a0f3341ccc40b69c0402bc9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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