Hacker0x01 / react-datepicker

A simple and reusable datepicker component for React
https://reactdatepicker.com/
MIT License
8.1k stars 2.24k forks source link

Open prop is not being respected by onInputClick #4351

Open barettjfed opened 1 year ago

barettjfed commented 1 year ago

Describe the bug The onInputClick function on line 724 in index.jsx is not taking into consideration if the calendar should be open or not and it is setting the open state to true when the calendar may not be open. This is causing unexpected behavior with things like onBlur which rely on the open to be false to trigger the callback.

onInputClick = () => {
    if (!this.props.disabled && !this.props.readOnly) {
      this.setOpen(true);
    }

    this.props.onInputClick();
};

To Reproduce Steps to reproduce the behavior:

Using this component

const [selected, setSelected] = useState(new Date());

<DatePicker
  selected={selected}
  onChange={(val) => {
    setSelected(val);
  }}
  preventOpenOnFocus={true}
  onBlur={() => {
    alert("Blur triggered");
  }}
  open={false}
/>
  1. Focus the field by clicking the input

  2. Click outside of the component

  3. Notice that the alert was not triggered

  4. Unmount/Refresh component and rerender

  5. Focus the field by tabbing into it (Not from clicking)

  6. Click out of the field

  7. Notice that the Alert was then triggered.

Expected behavior Clicking the field should not set open to true if the calendar is not opened.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

Additional context @martijnrusschen I could provide a PR to fix this issue, but not familiar with how to do that, or writing unit tests to verify.

barettjfed commented 1 year ago

I think this is somewhat related to #2028

barettjfed commented 1 year ago

Adding to this I think I found a work around for my issue.

By passing prop showTimeInput={true} it will allow the onBlur event to trigger. Then manually setting the value will keep it in sync with the selected value.

<DatePicker
  selected={selected}
  value={value}
  ref={ref}
  onChange={(val) => {
    setSelected(val);
  }}
  onBlur={() => {
    setValue(formatDate(selected));
  }}
  showTimeInput={true}
  open={false}
/>
github-actions[bot] commented 5 months ago

This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 10 days.