Skip to content

Commit f84a225

Browse files
authored
Merge pull request #1107 from coseeian/focus
fix: restore focus after search submission (#914)
2 parents fb187bc + 113555c commit f84a225

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/components/SearchProvider/index.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,6 @@ const SearchProvider = ({
126126
currentLocale={currentLocale as string}
127127
onSearchChange={handleSearchTermChange}
128128
uiTranslations={uiTranslations}
129-
key={searchTerm}
130129
/>
131130
);
132131
};

src/components/SearchResults/index.tsx

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useMemo, useRef, useState } from "preact/hooks";
1+
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
22
import { Icon } from "../Icon";
33

44
type SearchResult = {
@@ -23,8 +23,24 @@ const SearchResults = ({
2323
uiTranslations,
2424
}: SearchResultProps) => {
2525
const inputRef = useRef<HTMLInputElement>(null);
26+
const clearButtonRef = useRef<HTMLButtonElement>(null);
2627
const [currentFilter, setCurrentFilter] = useState("");
2728
const [isInputEdited, setInputEdited] = useState(false);
29+
const prevIsInputEdited = useRef(isInputEdited);
30+
31+
// Reset filter and input state when search term changes
32+
useEffect(() => {
33+
setCurrentFilter("");
34+
setInputEdited(false);
35+
}, [searchTerm]);
36+
37+
// Focus clear button when transitioning from edited to not edited
38+
useEffect(() => {
39+
if (prevIsInputEdited.current && !isInputEdited && clearButtonRef.current) {
40+
clearButtonRef.current.focus();
41+
}
42+
prevIsInputEdited.current = isInputEdited;
43+
}, [isInputEdited]);
2844

2945
const allUniqueCategoriesForResults = useMemo(() => {
3046
const categories = results.map((result) => result.category);
@@ -140,6 +156,7 @@ const SearchResults = ({
140156
</button>
141157
) : (
142158
<button
159+
ref={clearButtonRef}
143160
type="reset"
144161
class="absolute right-0 top-0 px-[22px] py-[13px]"
145162
onClick={clearInput}

0 commit comments

Comments
 (0)