Search code examples
reactjsreact-datepicker

React DatePicker not getting closed after the date selection


I am trying to use react-hook-form with react-datepicker. I am using a button to open the datepicker, and trying to close it once the selection of a new date is made.

enter image description here

Below is the code-sandbox I made showing the exact problem I am facing.

https://codesandbox.io/p/devbox/react-datepicker-qwfyfs?file=%2Fsrc%2FDatePicker.jsx%3A105%2C33

The control is not even going to the onChange in the DatePicker component while trying to debug. The DatePicker component can only be closed by clicking again on the button.

Any help is much appreciated


Solution

  • Your {...props} seems to overwrite the onChange logic. So you can remove the {...props} if not needed or if it does then put it first so that it does not overwrite the rest logic.

              <DatePicker
                {...props}
                inline
                selected={selected}
                onChange={(date) => {
                  console.log("event");
                  try {
                    handleChange(date);
                  } catch (err) {
                    console.log("error :", err);
                  } finally {
                    setIsOpen(false);
                  }
                }}
                calendarStartDay={1}
              />