Skip to content

YearPicker: Enter key does not select year when selected is null/undefined #6298

Description

@SaiBalaji202

Describe the bug
In the YearPicker (showYearPicker) of ReactDatePicker, pressing the Enter key does not select a year when the initial selected value is null or undefined.

However, mouse interaction works correctly and allows selecting a year even when no initial value is set.

This behavior is inconsistent with:

  • Default DatePicker (day picker)
  • MonthPicker

where keyboard selection works regardless of the initial selected value.


To Reproduce

const Default = () => {
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);

  const handleChange = (date: Date | null) => {
    setSelectedDate(date);
  };

  return (
    <DatePicker
      selected={selectedDate}
      onChange={handleChange}
      showYearPicker
    />
  );
};

render(Default);

Steps:

  1. Open the DatePicker
  2. Navigate between years using arrow keys
  3. Press Enter

Expected behavior

  • Pressing Enter should select the currently focused year
  • Behavior should be consistent with mouse interaction and other picker modes
  • Selection should work even when selected is initially null

Actual behavior

  • Pressing Enter does nothing when selected is null
  • Year is not selected
  • onChange / onSelect is not triggered

Root Cause

In src/year.tsx:

case KeyType.Enter:
  if (this.props.selected == null) {
    break;
  }

This early exit prevents selection when selected is null.


Additional context

  • There is an existing test enforcing this behavior:

    • Prevents onSelect from being called when selected is null
  • This behavior appears unintended and inconsistent with other pickers

  • Likely introduced for test coverage rather than UX correctness


Suggested fix

  • Remove the selected == null guard for Enter key handling
  • Allow selection based on the currently focused/preselected year
  • Update/remove the corresponding test enforcing the incorrect behavior

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions