Using a callback on click of react-date-range defined ranges

Solution 1:

I had the same issue, here is my workaround ;

while selecting ranges it updates both selection values in the very first click.

onDateRangeChanged= () => {
.....
if(ranges.selection.startDate !== ranges.selection.endDate){
      const result = calculateDateRangeFromTwoDates(ranges);
      if(result.specificTimeSpan === true)
          toggleRangePicker();
    }
.....
}

and with the calculator below u can extract whether your dates is defined range or not (of course code below can be refactored like reading from a Json file etc.)

export const calculateDateRangeFromTwoDates = (ranges: any) => {
  const beginDate = moment(ranges.selection.startDate);
  const endDate = moment(ranges.selection.endDate);
  const today = moment();
  let text = '';
  let specificTimeSpan = true;
  const duration = moment.duration(endDate.diff(beginDate));
  const selectedDateDifference = duration.get('days');

  switch (selectedDateDifference) {
    case 30:
    case 29:
      text = moment(endDate).isSame(today, 'month') ? 'This Month' : 'Last Month';
      break;
    case 7:
    case 6:
      text = moment(endDate).isSame(today, 'week') ? 'This Week' : 'Last Week';
      break;
    case 1:
    case 0:
      text = moment(endDate).isSame(today, 'day') ? 'Today' : 'Yesterday';
      break;
    default:
      text = `
      ${moment(ranges.selection.startDate).format('MM/DD/YYYY')} - ${moment(ranges.selection.endDate).format(
        'MM/DD/YYYY',
      )}
      `;
      specificTimeSpan = false;
      break;
  }

  return ({
    text,
    specificTimeSpan
  })
};