diff --git a/src/index.jsx b/src/index.jsx index bc8594954..89885ec7a 100644 --- a/src/index.jsx +++ b/src/index.jsx @@ -542,21 +542,14 @@ export default class DatePicker extends React.Component { if ( this.props.showTimeSelectOnly && this.props.selected && + date && !isSameDay(date, this.props.selected) ) { - if (date == null) { - date = set(this.props.selected, { - hours: getHours(this.props.selected), - minutes: getMinutes(this.props.selected), - seconds: getSeconds(this.props.selected), - }); - } else { - date = set(this.props.selected, { - hours: getHours(date), - minutes: getMinutes(date), - seconds: getSeconds(date), - }); - } + date = set(this.props.selected, { + hours: getHours(date), + minutes: getMinutes(date), + seconds: getSeconds(date), + }); } if (date || !event.target.value) { this.setSelected(date, event, true); diff --git a/test/datepicker_test.test.js b/test/datepicker_test.test.js index 1f93294bf..9e0285dfe 100644 --- a/test/datepicker_test.test.js +++ b/test/datepicker_test.test.js @@ -4,6 +4,7 @@ import { findDOMNode } from "react-dom"; import TestUtils from "react-dom/test-utils"; import { enUS, enGB } from "date-fns/locale"; import { mount } from "enzyme"; +import { render, fireEvent } from "@testing-library/react"; import defer from "lodash/defer"; import DatePicker, { registerLocale } from "../src/index.jsx"; import Day from "../src/day.jsx"; @@ -2102,6 +2103,55 @@ describe("DatePicker", () => { }); }); + it("clears the selected date on empty date input", () => { + let date = "2023-10-23 10:00:00"; + const selected = utils.newDate(date); + + const { container: datepicker } = render( + { + date = d; + }} + showTimeSelect + dateFormat="MMMM d, yyyy h:mm aa" + />, + ); + + const input = datepicker.querySelector( + ".react-datepicker__input-container > input", + ); + fireEvent.change(input, { target: { value: "" } }); + + expect(date).toBe(null); + }); + + it("clears the selected date on empty date input with showTimeSelectOnly", () => { + const format = "h:mm aa"; + + let date = "2022-02-24 10:00:00"; + const selected = utils.newDate(date); + + const { container: datepicker } = render( + { + date = d; + }} + showTimeSelectOnly + dateFormat={format} + timeFormat={format} + />, + ); + + const input = datepicker.querySelector( + ".react-datepicker__input-container > input", + ); + fireEvent.change(input, { target: { value: "" } }); + + expect(date).toBe(null); + }); + it("should selected month when specified minDate same month", () => { const selected = utils.newDate("2023-01-09"); let date = null;