When loading react-datepicker with redux form, sometimes there will be some initial values provided by the user, when we load these into the datepicker I believe (please correct me if I am wrong) that we actually ignore any requested display formats or locales provided by the user if they supply the selected prop.
Offending lines of code appears to be here: https://github.com/Hacker0x01/react-datepicker/blob/master/src/index.jsx#L180-L183
As I say, this is only when the datepicker is first initialised, locale and dateFormat is recognised onChange :)
/**
*
* Datepicker
*
*/
import 'react-datepicker/dist/react-datepicker.css'
import React from 'react'
import PropTypes from 'prop-types'
import ReactDatepicker from 'react-datepicker'
import moment from 'moment'
moment.locale('en-gb')
class Datepicker extends React.Component {
state = {
selectedDate: moment(this.props.input.value),
}
handleChange = (date) => {
this.setState({
selectedDate: date,
})
this.props.input.onChange(date)
}
render() {
const { input, meta, placeholder } = this.props
const filterDates = (date) => moment(date) >= moment().startOf('day')
return (
<ReactDatepicker
{...input}
className="form-control"
filterDate={filterDates}
placeholderText={placeholder}
isClearable
locale="en-gb"
showMonthDropdown
showYearDropdown
dropdownMode="select"
dateFormat='DD/MM/YYYY'
selected={this.state.selectedDate}
onChange={this.handleChange}
onBlur={input.onBlur}
/>
)
}
}
Datepicker.propTypes = {
input: PropTypes.object,
meta: PropTypes.object,
placeholder: PropTypes.string,
}
export default Datepicker
My current code incase anyone would like to point out I'm doing something wrong :)
Thanks guys, doing an awesome job!
+1 this is a pain. The value in selected should receive the dateFormat prop. I am not able to find a workaround for supplying a moment object to selected and have it display initially in the correct format. In my case, I have dateFormat set to 'lll'.
This does not work for me:
<DatePicker
selected={moment("12-25-1995", "MM-DD-YYYY")}
onChange={this.handleChange}
dateFormat="LLL"
/>
The initial date is not displayed in LLL format.
Same problem here, sadly. Has anyone found a workaround for this?
Never mind, I think I had a different problem. I had assumed the input date string would be initially formatted based on "dateFormat", but that doesn't appear to be the case. I'm formatting the date string when the rest of the form data is prepared and that seems to work fine.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Most helpful comment
+1 this is a pain. The value in selected should receive the dateFormat prop. I am not able to find a workaround for supplying a moment object to selected and have it display initially in the correct format. In my case, I have dateFormat set to 'lll'.
This does not work for me:
The initial date is not displayed in LLL format.