diff --git a/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx b/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx
index 459daa35f98..85ce2ee4d6d 100644
--- a/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx
+++ b/packages/ra-ui-materialui/src/input/AutocompleteInput.spec.tsx
@@ -26,6 +26,7 @@ import {
InsideReferenceInputOnChange,
WithInputProps,
OnCreate,
+ OnCreateWithAutoSelect,
OnCreateSlow,
CreateLabel,
CreateItemLabel,
@@ -1212,6 +1213,18 @@ describe('', () => {
});
describe('onCreate', () => {
+ it('should keep a clicked choice on blur when autoSelect is enabled', async () => {
+ render();
+ const input = (await screen.findByLabelText(
+ 'Author'
+ )) as HTMLInputElement;
+
+ fireEvent.focus(input);
+ fireEvent.click(await screen.findByText('Victor Hugo'));
+ fireEvent.blur(input);
+
+ expect(input.value).toEqual('Victor Hugo');
+ });
it("shouldn't include an option with the create label when the input is empty", async () => {
render();
const input = (await screen.findByLabelText(
diff --git a/packages/ra-ui-materialui/src/input/AutocompleteInput.stories.tsx b/packages/ra-ui-materialui/src/input/AutocompleteInput.stories.tsx
index bf5d25229ed..95e95c15d44 100644
--- a/packages/ra-ui-materialui/src/input/AutocompleteInput.stories.tsx
+++ b/packages/ra-ui-materialui/src/input/AutocompleteInput.stories.tsx
@@ -375,6 +375,12 @@ OnCreate.argTypes = {
},
};
+export const OnCreateWithAutoSelect = () => (
+
+
+
+);
+
const AutocompleteWithCreateInReferenceInput = () => {
const [create] = useCreate();
const handleCreateAuthor = async (authorName?: string) => {
diff --git a/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx b/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx
index d5e8eb96a06..be86cb0c412 100644
--- a/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx
+++ b/packages/ra-ui-materialui/src/input/AutocompleteInput.tsx
@@ -619,6 +619,13 @@ If you provided a React element for the optionText prop, you must also provide t
(event: any, newValue: any, reason: AutocompleteChangeReason) => {
// This prevents auto-submitting a form inside a dialog passed to the `create` prop
event.preventDefault();
+ if (
+ reason === 'blur' &&
+ typeof newValue === 'string' &&
+ doesQueryMatchSelection(newValue)
+ ) {
+ return;
+ }
if (reason === 'createOption') {
// When users press the enter key after typing a new value, we can handle it as if they clicked on the create option
handleChangeWithCreateSupport(
@@ -634,7 +641,12 @@ If you provided a React element for the optionText prop, you must also provide t
newValue != null ? newValue : emptyValue
);
},
- [emptyValue, getCreateItem, handleChangeWithCreateSupport]
+ [
+ doesQueryMatchSelection,
+ emptyValue,
+ getCreateItem,
+ handleChangeWithCreateSupport,
+ ]
);
const oneSecondHasPassed = useTimeout(1000, filterValue);