Search code examples
reactjsreact-datepickerreact-daterange-picker

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


enter image description here

How can we add a callback when clicked the encircled ranges? I want to change the input placeholder based on the range picked. For example the user clicked "This week" so the placeholder also on the right should be changed to "This week". I've red the documentation but I cant find thing I need. Thank you so much for your help in advance! Here's a snippet of my code.

  const [dateState, setDateState] = useState<any>([
    { startDate: null, endDate: null, key: "selection" },
  ]);

      {openDateRange && (
        <DateRangePicker
          className="date-range"
          editableDateInputs={true}
          onChange={(item) => setDateState([item.selection])}
          moveRangeOnFirstSelection={false}
          ranges={dateState}
        />
      )}

Solution

  • 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
      })
    };