Skip to content

Commit

Permalink
Merge pull request #12 from aaronfreeman/focus-search-box
Browse files Browse the repository at this point in the history
fix: focus on search box when select opens
  • Loading branch information
onesine authored Feb 24, 2023
2 parents f32d505 + 0e25ba2 commit 409ffc9
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ dist
.env.development.local
.env.test.local
.env.production.local
.yarn
.yarnrc.yml

npm-debug.log*
yarn-debug.log*
Expand Down
15 changes: 7 additions & 8 deletions src/components/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext } from "react";
import React, { forwardRef, useContext } from "react";

import { SearchIcon } from "./Icons";
import { SelectContext } from "./SelectProvider";
Expand All @@ -10,12 +10,10 @@ interface SearchInputProps {
name?: string;
}

const SearchInput: React.FC<SearchInputProps> = ({
placeholder = "",
value = "",
onChange,
name = ""
}) => {
const SearchInput = forwardRef<HTMLInputElement, SearchInputProps>(function SearchInput(
{ placeholder = "", value = "", onChange, name = "" },
ref
) {
const { classNames } = useContext(SelectContext);
return (
<div
Expand All @@ -33,6 +31,7 @@ const SearchInput: React.FC<SearchInputProps> = ({
}
/>
<input
ref={ref}
className={
classNames && classNames.searchBox
? classNames.searchBox
Expand All @@ -46,6 +45,6 @@ const SearchInput: React.FC<SearchInputProps> = ({
/>
</div>
);
};
});

export default SearchInput;
12 changes: 12 additions & 0 deletions src/components/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const Select: React.FC<SelectProps> = ({
const [list, setList] = useState<ListOption>(options);
const [inputValue, setInputValue] = useState<string>("");
const ref = useRef<HTMLDivElement>(null);
const searchBoxRef = useRef<HTMLInputElement>(null);

useEffect(() => {
const formatItem = (item: Option) => {
Expand All @@ -91,6 +92,16 @@ const Select: React.FC<SelectProps> = ({
);
}, [options]);

useEffect(() => {
if (isSearchable) {
if (open) {
searchBoxRef.current?.select();
} else {
setInputValue("");
}
}
}, [open, isSearchable]);

const toggle = useCallback(() => {
if (!isDisabled) {
setOpen(!open);
Expand Down Expand Up @@ -297,6 +308,7 @@ const Select: React.FC<SelectProps> = ({
>
{isSearchable && (
<SearchInput
ref={searchBoxRef}
value={inputValue}
placeholder={searchInputPlaceholder}
onChange={e => setInputValue(e.target.value)}
Expand Down

0 comments on commit 409ffc9

Please # to comment.