React-datepicker: Add clarity on how to coerce the date from moment to an ISO date string

Created on 28 Oct 2016  路  3Comments  路  Source: Hacker0x01/react-datepicker

I had issues setting up react-datepicker as the component deals with moment objects but this does not play so well when used with the rest of my app that is using Redux and is also sending request to an external API.

I think this is a common setup requirement to have the date available to the rest of the react app in a string format once the date has been picked.

With some help from a friend we got this working but it definitley took a bit of mucking around having moment objects available in certain places and date strings available in other places.

Here is the code I got working for anyone having these issues, would be great to include a few of these clues in the README or tips also just not quite sure what to emphasise or where this should best be put.

Open to suggestions and happy to create a pull request to update documentation if that would be welcome.

import React, { PropTypes } from 'react'
import moment from 'moment'
import DatePicker from 'react-datepicker'

export default class DateField extends React.Component {
  static propTypes = {
    value: PropTypes.string,
    onChange: PropTypes.func,
    onBlur: PropTypes.func
  };

  constructor (props) {
    super(props)
    this.state = {
      value: props.value
    }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange (date) {
    const formattedDate = date && date.format()
    this.setState({value: formattedDate})
    this.props.onChange(formattedDate)
  }

  render () {
    const {value} = this.state
    const attrs = {}
    if (value) {
      attrs.selected = moment(value)
    }
    return (
      <DatePicker
        type="datetime"
        dateFormat="DD MMM YYYY"
        onBlur={this.props.onBlur}
        onChange={this.handleChange}
        {...attrs}
        />
    )
  }
}







Most helpful comment

I had the same issues you had. My redux application state should store a string while the onChange for the date picker has a Moment object as argument and the value prop for the picker takes a moment object, not a string. Thank you for for code sample.

All 3 comments

date.format() will actually give you an ISO timestamp. `date.format('YYYY-MM-DD') will give you an ISO 8601 date.

I had the same issues you had. My redux application state should store a string while the onChange for the date picker has a Moment object as argument and the value prop for the picker takes a moment object, not a string. Thank you for for code sample.

Moment.js was removed in #1527, starting v2.0.0, this package doesn't use Moment anymore.

Was this page helpful?
0 / 5 - 0 ratings