Skip to content

Commit 10075aa

Browse files
committed
fix: add debounced prop and ux to mui search input component
Signed-off-by: Tomás Castillo <tcastilloboireau@gmail.com>
1 parent 54bca4e commit 10075aa

1 file changed

Lines changed: 30 additions & 11 deletions

File tree

src/components/mui/search-input.js

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,36 +11,55 @@
1111
* limitations under the License.
1212
* */
1313

14-
import React, { useEffect, useState } from "react";
15-
import { TextField, IconButton } from "@mui/material";
14+
import React, { useEffect, useState, useCallback } from "react";
15+
import { TextField, IconButton, InputAdornment } from "@mui/material";
1616
import SearchIcon from "@mui/icons-material/Search";
1717
import ClearIcon from "@mui/icons-material/Clear";
18+
import { debounce } from "lodash";
19+
import { DEBOUNCE_WAIT } from "../../utils/constants";
1820

19-
const SearchInput = ({ term, onSearch, placeholder = "Search..." }) => {
21+
const SearchInput = ({ term, onSearch, placeholder = "Search...", debounced }) => {
2022
const [searchTerm, setSearchTerm] = useState(term);
2123

2224
useEffect(() => {
2325
setSearchTerm(term || "");
2426
}, [term]);
2527

26-
const handleSearch = (ev) => {
27-
if (ev.key === "Enter") {
28-
onSearch(searchTerm);
29-
}
30-
};
31-
3228
const handleClear = () => {
3329
setSearchTerm("");
3430
onSearch("");
3531
};
3632

33+
const onSearchDebounced = useCallback(
34+
debounced ? debounce((value) => onSearch(value), DEBOUNCE_WAIT) : null,
35+
[onSearch, debounced]
36+
);
37+
38+
useEffect(() => () => onSearchDebounced?.cancel(), [onSearchDebounced]);
39+
40+
const handleChange = (value) => {
41+
setSearchTerm(value);
42+
if (debounced) onSearchDebounced(value);
43+
};
44+
45+
const handleKeyDown = (ev) => {
46+
if (!debounced && ev.key === "Enter") {
47+
onSearch(searchTerm);
48+
}
49+
};
50+
3751
return (
3852
<TextField
3953
variant="outlined"
4054
value={searchTerm}
4155
placeholder={placeholder}
4256
slotProps={{
4357
input: {
58+
startAdornment: (
59+
<InputAdornment position="start">
60+
<SearchIcon sx={{ color: "#0000008F" }} />
61+
</InputAdornment>
62+
),
4463
endAdornment: term ? (
4564
<IconButton
4665
size="small"
@@ -56,8 +75,8 @@ const SearchInput = ({ term, onSearch, placeholder = "Search..." }) => {
5675
)
5776
}
5877
}}
59-
onChange={(event) => setSearchTerm(event.target.value)}
60-
onKeyDown={handleSearch}
78+
onChange={(ev) => handleChange(ev.target.value)}
79+
onKeyDown={handleKeyDown}
6180
fullWidth
6281
sx={{
6382
"& .MuiOutlinedInput-root": {

0 commit comments

Comments
 (0)