diff --git a/packages/react/src/components/DatePicker/DatePicker-test.js b/packages/react/src/components/DatePicker/DatePicker-test.js index ea3ab3c0e4f4..9e6604577537 100644 --- a/packages/react/src/components/DatePicker/DatePicker-test.js +++ b/packages/react/src/components/DatePicker/DatePicker-test.js @@ -8,7 +8,7 @@ import React, { useState } from 'react'; import DatePicker from './DatePicker'; import DatePickerInput from '../DatePickerInput'; -import { render, screen } from '@testing-library/react'; +import { render, screen, fireEvent } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Slug } from '../Slug'; @@ -100,6 +100,37 @@ describe('DatePicker', () => { ).toBeInTheDocument(); }); + it('should not fire onChange handler when clicking outside the datepicker in range mode', () => { + const handleChange = jest.fn(); + const { getByLabelText, getByText } = render( + + + + + ); + const startDateInput = getByLabelText('Start date'); + const endDateInput = getByLabelText('End date'); + // Change the dates + fireEvent.change(startDateInput, { target: { value: '01/01/2023' } }); + fireEvent.change(endDateInput, { target: { value: '01/07/2023' } }); + // Simulate a click event outside the datepicker + fireEvent.click(document.body); + fireEvent.focus(startDateInput); + fireEvent.click(document.body); + expect(handleChange).not.toHaveBeenCalled(); + }); + it('should render the children as expected', () => { render( {}} dateFormat="m/d/Y" datePickerType="range"> diff --git a/packages/react/src/components/DatePicker/plugins/rangePlugin.js b/packages/react/src/components/DatePicker/plugins/rangePlugin.js index 60408170d91c..754410aa1c15 100644 --- a/packages/react/src/components/DatePicker/plugins/rangePlugin.js +++ b/packages/react/src/components/DatePicker/plugins/rangePlugin.js @@ -18,11 +18,12 @@ export default (config) => { // If `triggerChange` is `true`, `onValueUpdate` Flatpickr event is fired // where Flatpickr's range plugin takes care of fixing the first `` if (!triggerChange) { - const { _input: inputFrom } = fp; - const { input: inputTo } = config; - [inputFrom, inputTo].forEach((input, i) => { + const { _input: inputDates } = fp; + const inputDatesArray = inputDates.value.split(' '); + fp.close(); + [inputDatesArray[0], inputDatesArray[2]].forEach((input, i) => { if (input) { - input.value = !dates[i] + input = !dates[i] ? '' : fp.formatDate(new Date(dates[i]), fp.config.dateFormat); }