Skip to content

Instantly share code, notes, and snippets.

@0xF013
Created June 14, 2016 09:58
Show Gist options
  • Save 0xF013/941c63f1f19f41e967cb4d887ed8d100 to your computer and use it in GitHub Desktop.
Save 0xF013/941c63f1f19f41e967cb4d887ed8d100 to your computer and use it in GitHub Desktop.
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { default as Decorated } from 'react-widgets/lib/DateTimePicker';
import moment from 'lib/moment';
export default class DateTimePicker extends Component {
static propTypes = {
value: PropTypes.any,
format: PropTypes.string,
onChange: PropTypes.func,
readOnly: PropTypes.bool,
disabled: PropTypes.bool,
};
componentDidMount() {
const input = ReactDOM.findDOMNode(this).getElementsByTagName('input')[0];
input.addEventListener('keypress', e => {
if (e.keyCode === 13) {
this.handleChange(input.value);
}
});
}
handleChange(date) {
return this.props.onChange(date ? moment(date) : date);
}
render() {
const {
value,
readOnly = false,
disabled = false,
format = 'MM/DD/YYYY h:mm:ss a',
} = this.props;
const parser = dateStr =>
dateStr ? moment(dateStr, format).toDate() : null;
const formatter = date =>
date ? moment(date).format(format) : '';
let modifiedValue = value;
if (!value) {
modifiedValue = null;
} else {
if (typeof modifiedValue === 'string') {
modifiedValue = moment(value, format);
} else {
if (!value.isValid()) {
modifiedValue = null;
}
}
}
return (
<Decorated
/* convert the value to a normal date */
readOnly={ readOnly }
disabled={ disabled }
value={ modifiedValue ? modifiedValue.toDate() : null }
defaultCurrentDate={ moment().startOf('day').toDate() }
/* convert back to a Moment instance */
onChange={ ::this.handleChange }
format={ formatter }
parse={ parser }
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment