Search code examples
javascriptreact-day-picker

react-day-picker doesn't close if keepfocus is set to false


I was trying to make a simple implementation of react-day-picker. But I found a problem when trying to close DayPicker container when it is triggered from DayPickerInput and the property keepFocus is set to false.

<DayPickerInput
    keepFocus={false}
    placeholder="DD/MM/YYYY"
    format="DD/MM/YYYY"
/>

Here is the codesandbox: https://codesandbox.io/s/0mn32ryl0n

If you click inside the input the daypicker overlay is displayed correctly and if you click in a empty area of the overlay, then the overlay gets focused and it will be focused until you select one day, otherwise it won't be closed. So if you click in an area outside the overlay it can't be closed automatically.

The question would be, if this is the intended behavior or maybe I'm missing something. How can I close the DayPicker if a day is not selected and the overlay is already focused?


Solution

  • I end up doing something like this,

    let dayPickerInputRef = null;
    function Example() {
      return (
        <div name="main-container">
          <h3>DayPickerInput</h3>
          <DayPickerInput
            ref={ref => (dayPickerInputRef = ref)}
            keepFocus={false}
            placeholder="DD/MM/YYYY"
            format="DD/MM/YYYY" 
            dayPickerProps = {{
              onBlur: () => {
                setTimeout(() => {
                  const elClicked = document.activeElement,
                    container = document.getElementsByName(`main-container`);
                  if (container && !container[0].contains(elClicked)) {
                    dayPickerInputRef.hideDayPicker();
                  }
                }, 1);
              }
            }}
          />
        </div>
      );
    }