hypeserver / react-date-range

A React component for choosing dates and date ranges.
MIT License
2.57k stars 658 forks source link

Possible to put a limit to the range selection? #619

Open eitai opened 11 months ago

eitai commented 11 months ago

Possible to put a limit to the range selection?

umakantp commented 6 months ago

yes. There is minDate and maxDate prop for it.

x-Foz3R-x commented 4 months ago

You can achieve it with this workaround

  const [state, setState] = useState({ startDate: new Date(), endDate: new Date(), key: "your-key" });
  const [focusedRange, setFocusedRange] = useState([0, 0] as RangeFocus);
  const [selecting, setSelecting] = useState(false);

  // Selection limited min/max Dates
  const minDateLimit = addDays(state.startDate, -DAYS_LIMIT + 1)
  const maxDateLimit = addDays(state.startDate, DAYS_LIMIT - 1)

  const minDate = selecting ? minDateLimit : addDays(new Date(), -300)
  const maxDate = selecting ? maxDateLimit : addDays(new Date(), 900)

  const handleFocusChange = (newFocusedRange: RangeFocus) => {
    setFocusedRange(newFocusedRange);
    if (newFocusedRange[1] === 1) setSelecting(true);
    else setSelecting(false);
  };

return (
  <DateRange
    ranges={[state]}
    focusedRange={focusedRange}
    onRangeFocusChange={handleFocusChange}
    minDate={minDate}
    maxDate={maxDate}
    // *other props*
  />
);

I hope it helped :))