Search code examples
reactjsdatepickerreact-datepicker

React-DatePicker - how to disable closing on start date selection


I develop DatePicker for components library, and using the react-datepicker npm to do so.

The desired behavior is that the user click the input, the date picker will open, the user will select 2 dates, when click on the 2nd date the DatePicker will close.

The issue is that the picker is being closed on the start date selection.

I removed all my code, and use the exact example displayed in the npm demo:

https://reactdatepicker.com/#example-date-range-using-input-with-clear-button

still the date picker is closing on the start date select.

I tried adding shouldCloseOnSelect set to true but then it doesn't close on end date select as well.

how to prevent the closing on the start date, and allow it on the end date.

current code:

const MyDatePicker = () => {
  const [dateRange, setDateRange] = useState([null, null]);
  const [testStart, testEnd] = dateRange;
  return (
    <ReactDatePicker
      selectsRange={true}
      startDate={testStart}
      endDate={testEnd}
      onChange={(update: any) => {
        setDateRange(update);
      }}
      isClearable={true}
    />
  );

}

Solution

  • It's a known issue - Github issue

    I work around it using open, onInputClick and onClickOutside props, like this:

    const MyDatePicker = () => {
     const [isOpen, setIsOpen] = useState(false);
      return (
        <ReactDatePicker
          onInputClick={() => setIsOpen(true)}
          onClickOutside={() => setIsOpen(false)}
          open={isOpen}
          selectsRange={true}
          startDate={testStart}
          endDate={testEnd}
          onChange={(update: any) => {
            setDateRange(update);
            if (update[1]) {
              setIsOpen(false);
            }
          }}
          isClearable={true}
        />
      );