Skip to content

Instantly share code, notes, and snippets.

@json2d
Last active May 26, 2017 13:04
Show Gist options
  • Save json2d/6b16cf414397b3d1266b1c1bf5a0d9f3 to your computer and use it in GitHub Desktop.
Save json2d/6b16cf414397b3d1266b1c1bf5a0d9f3 to your computer and use it in GitHub Desktop.
'react-datepicker' integration with 'redux-form@5.2.3'
import React, { Component } from 'react'
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
export class DateInput extends Component{
constructor (props) {
super(props);
if(this.props.field.value) {
this.state = { selectedDate: moment(this.props.field.value) }
}else{
this.state = { selectedDate: undefined }
}
}
syncDatePickerWithField = () => {
if(this.state.selectedDate && this.props.field.value && this.props.field.value !== this.state.selectedDate.format(DATE_FORMAT)) {
console.log('unsynced datepicker field detected')
//console.log(this.props.field.value, '!=', this.state.selectedDate.format(DATE_FORMAT))
this.handleChange(moment(this.props.field.value)) // ❗ this line is needed to correctly display the formatted date in the input field
}
}
componentWillMount() {
this.syncDatePickerWithField()
}
componentDidUpdate() {
this.syncDatePickerWithField()
}
handleChange = (date) => {
this.setState({ selectedDate: date });
this.props.field.onChange(date.format(DATE_FORMAT)) // ❗ this line is needed to correctly display the formatted date in the input field
}
render() {
const { field, label, ...rest } = this.props
return (
<div>
<label>{label}</label>
<DatePicker {...field} dateFormat={DATE_FORMAT} selected={this.state.selectedDate} onChange={this.handleChange}/>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment