2017-09-09 19:39:10 -06:00
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import React from 'react';
|
2016-11-17 04:08:37 -08:00
|
|
|
import DateTime from 'react-datetime';
|
2017-11-23 22:44:56 -08:00
|
|
|
import moment from 'moment';
|
2016-11-17 04:08:37 -08:00
|
|
|
|
2017-11-27 14:19:38 -08:00
|
|
|
export default class DateControl extends React.Component {
|
2016-12-01 16:28:33 -02:00
|
|
|
componentDidMount() {
|
2017-11-27 14:19:38 -08:00
|
|
|
const { value, field, onChange } = this.props;
|
2017-11-27 21:13:02 -05:00
|
|
|
this.format = field.get('format');
|
2017-11-27 21:17:17 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Set the current date as default value if no default value is provided. An
|
|
|
|
* empty string means the value is intentionally blank.
|
|
|
|
*/
|
|
|
|
if (!value && value !== '') {
|
2017-11-27 21:13:02 -05:00
|
|
|
this.handleChange(new Date());
|
2016-12-01 16:28:33 -02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 21:13:02 -05:00
|
|
|
handleChange = datetime => {
|
2017-11-27 22:33:54 -05:00
|
|
|
const { onChange } = this.props;
|
|
|
|
if (!this.format || datetime === '') {
|
|
|
|
onChange(datetime);
|
|
|
|
} else {
|
|
|
|
const formattedValue = moment(datetime).format(this.format);
|
|
|
|
onChange(formattedValue);
|
|
|
|
}
|
2016-11-17 04:08:37 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
render() {
|
2017-11-27 21:13:02 -05:00
|
|
|
const { includeTime, value } = this.props;
|
|
|
|
const format = this.format || moment.defaultFormat;
|
2017-11-27 14:19:38 -08:00
|
|
|
return (<DateTime
|
2017-11-27 15:06:21 -08:00
|
|
|
timeFormat={!!includeTime}
|
2017-11-27 14:19:38 -08:00
|
|
|
value={moment(value, format)}
|
|
|
|
onChange={this.handleChange}
|
2016-11-17 04:08:37 -08:00
|
|
|
/>);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 14:19:38 -08:00
|
|
|
DateControl.propTypes = {
|
2016-11-17 04:08:37 -08:00
|
|
|
onChange: PropTypes.func.isRequired,
|
2017-11-23 22:44:56 -08:00
|
|
|
value: PropTypes.oneOfType([
|
|
|
|
PropTypes.object,
|
|
|
|
PropTypes.string,
|
|
|
|
]),
|
|
|
|
includeTime: PropTypes.bool,
|
2017-11-27 14:19:38 -08:00
|
|
|
field: PropTypes.object,
|
2016-11-17 04:08:37 -08:00
|
|
|
};
|