Struggling to get dates as strings from react-datepicker in React/Redux app. Back-end services operates with date fields as strings in format specific to front-end user language settings. Therefore it is easier to store dates as strings in Redux.
In pre 2.0.0 version react-datepicker operated with moment objects and conversion could be performed with momentDate.format().
Version 2.0.0 operates with vanilla JS dates. react-datepicker performs string
<-> Date
conversion with internal methods (formatDate
) which are not exported. Could not manage to access these functions.
Currently using work-around performing conversion with moment.js. Approach has disadvantages:
- moment.js and react-datepicker format masks does not match (different letter cases for an example)
- extra library dependency (moment.js)
Current code:
import React from 'react';
import OriginalDatepicker from 'react-datepicker';
import moment from 'moment';
const dateFormat = 'dd.MM.yyyy'; // Depends on user current locale.
const momentDateFormat = dateFormat.toUpperCase();
function parseDate(dateString) {
if (dateString) {
return moment(dateString, momentDateFormat).toDate();
} else {
return null;
}
}
function format(date) {
if (date) {
return moment(date).format(momentDateFormat);
} else {
return null;
}
}
const ApplicationSpecificDatepicker = props => {
if (props.hasOwnProperty('selectedString')) {
const { selectedString, ...remaining } = props;
props = { ...remaining, selected: parseDate(props.selectedString) };
}
const onChangeOverride = (...args) => {
if (props.onChangeAsString) {
const [date, ...remaining] = args;
const stringDate = format(date);
props.onChangeAsString(stringDate, ...remaining);
}
if (props.onChange) {
props.onChange(...args);
}
}
return (
<OriginalDatepicker
dateFormat={ dateFormat }
{ ...props }
onChange={ onChangeOverride }
/>
);
};
const DatepickerUsage = () => (
<ApplicationSpecificDatepicker selectedString={ '31.12.2018' }
onChangeAsString={ (date) => console.log(date) }
/>
);
What is recommended solution for accessing react-datepicker 2.0.0 input string values?