Skip to content

Commit

Permalink
Reset DateInput textValue on form reset (#6834)
Browse files Browse the repository at this point in the history
* Reset DateInput textValue on form reset

* Ensure dateinput is part of reset form

* Adjust scope of event listener

* Use native HTML element.form

* Leave story unchanged

* Update src/js/components/DateInput/DateInput.js

* Update src/js/components/DateInput/DateInput.js

---------

Co-authored-by: Jessica Filben <54560994+jcfilben@users.noreply.github.com>
  • Loading branch information
taysea and jcfilben committed Jun 29, 2023
1 parent ec9c0e8 commit 5a6ec98
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/js/components/DateInput/DateInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,23 @@ Use the icon prop instead.`,
}
}, [range, schema, textValue, reference, value]);

// textValue of MaskedInput is controlled.
// for uncontrolled forms, ensure the reset event
// resets the textValue
useEffect(() => {
const form = ref?.current?.form;
const handleFormReset = (e) => {
if (schema && ref.current && e.target.contains(ref.current)) {
setTextValue('');
}
};
// place the listener on the form directly. if listener is on window,
// the event could get blocked if caller has e.stopPropagation(), etc. in
// their form onReset
form?.addEventListener('reset', handleFormReset);
return () => form?.removeEventListener('reset', handleFormReset);
}, [schema, ref]);

// when format and not inline, whether to show the Calendar in a Drop
const [open, setOpen] = useState();

Expand Down
21 changes: 21 additions & 0 deletions src/js/components/DateInput/__tests__/DateInput-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1143,4 +1143,25 @@ describe('DateInput', () => {
);
expect(asFragment()).toMatchSnapshot();
});

test('reseting uncontrolled form should reset text value', async () => {
const user = userEvent.setup();

render(
// onReset e.stopPropagation() is testing to ensure
// the event won't be lost if caller adds custom reset
<Form onReset={(e) => e.stopPropagation()}>
<DateInput format="mm/dd/yyyy" name="date" />
<Button label="Reset" type="reset" />
</Form>,
);
const input = screen.getByRole('textbox');
await user.type(input, '09/09/2022');

expect(input).toHaveValue('09/09/2022');

await user.click(screen.getByRole('button', { name: 'Reset' }));

expect(input).toHaveValue('');
});
});

0 comments on commit 5a6ec98

Please sign in to comment.