I am trying to implement a cancel feature, where if a user clicks outside the react-dates date picker calendar something happens.
In my calendar component I am setting state for two properties - startDate
and endDate
but endDate
doesn't get set on the state. If I add breakpoints I can see it hits this and tries to set it with a value. If I add the callback function for state being updated, this never gets run, so something weird is happening that I can't resolve.
Why would state not update? There are no errors in the console.
Example code from my calendar component:
onDatesChange = ({ startDate, endDate }) => {
this.setState({ startDate, endDate });
if (startDate && endDate) {
this.props.onDatesPicked(startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD'));
}
};
onClose = () => {
const { startDate, endDate } = this.state;
if (!startDate || !endDate) {
this.props.onCancel();
}
};
render() {
const { startDate, endDate, focusedInput } = this.state;
return (
<div className={css.component}>
<DateRangePicker
displayFormat="DD MMM YYYY"
isOutsideRange={this.isOutsideRange}
startDate={startDate}
startDateId={START_DATE}
startDatePlaceholderText="Start date"
endDate={endDate}
endDateId={END_DATE}
endDatePlaceholderText="End date"
onDatesChange={this.onDatesChange}
focusedInput={focusedInput}
onFocusChange={this.onFocusChange}
firstDayOfWeek={1}
hideKeyboardShortcutsPanel
minimumNights={0}
withPortal
onClose={this.onClose}
/>
</div>
);
}
In the onClose
function never finds a value for endDate
even though setState
has already been called in onDatesChange
and has passed in a value. There are no issues with startDate
. If I comment out setting startDate
then endDate
does get set fine.
I am so confused...