Skip to content

Commit

Permalink
fix(AutoComplete): fix autocomplete behavior in forms by preventing s…
Browse files Browse the repository at this point in the history
…ubmissions on Enter keypress (#1350)
  • Loading branch information
ashbork authored Sep 17, 2024
1 parent f6ba4ab commit a2c12ca
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,25 @@ export const Examples = (): React.ReactElement => {
single
/>
</StoryDescriptor>

<StoryDescriptor title="Don't hide exact matches">
<AutoComplete
options={['Option 1']}
placeholder={placeholderText}
hideIfExactMatch={false}
/>
</StoryDescriptor>
<StoryDescriptor title="In a form">
<form
onSubmit={(e) => {
e.preventDefault();
// eslint-disable-next-line no-console
console.log('submit');
}}
>
<AutoComplete options={options} placeholder={placeholderText} />
</form>
</StoryDescriptor>
</>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,13 @@ export const AutoComplete = React.forwardRef<
};

const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
handleVisibilityChange(true);
if (virtualItemRef.current?.id && event.key === 'Enter') {
const isEnterKey = event.key === 'Enter';
if (virtualItemRef.current?.id && isEnterKey) {
handleAutoComplete([{ key: virtualItemRef.current?.id }]);
event.preventDefault();
}
if (!isEnterKey) {
handleVisibilityChange(true);
}
inputProps.onKeyDown?.(event);
};
Expand Down

0 comments on commit a2c12ca

Please sign in to comment.