Files
nobat724_front/components/doctors/search/AutoComplete.js
T

102 lines
2.6 KiB
JavaScript

import { Autocomplete, TextField } from "@mui/material";
import { useRef, useState, useEffect } from "react";
function AutoComplete({
data,
noneBg,
clearText,
inputValue,
placeholder,
handleSearch,
setInputValue,
setSelectedOption,
debounce = 500,
}) {
const typingTimeoutRef = useRef(null);
const [localInput, setLocalInput] = useState(inputValue || "");
useEffect(() => {
setLocalInput(inputValue || "");
}, [inputValue]);
useEffect(() => {
return () => {
if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
};
}, []);
const onInputChange = (_, newInputValue) => {
setLocalInput(newInputValue);
if (setInputValue) setInputValue(newInputValue);
if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
typingTimeoutRef.current = setTimeout(() => {
handleSearch(newInputValue);
}, debounce);
};
const onChange = (_, newValue) => {
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
typingTimeoutRef.current = null;
}
const val = newValue
? typeof newValue === "string"
? newValue
: newValue.name
: "";
setLocalInput(val);
setSelectedOption && setSelectedOption(newValue);
handleSearch(val);
if (setInputValue) setInputValue(val);
};
return (
<Autocomplete
freeSolo
options={Array.isArray(data) ? data : []} // ✅ همیشه آرایه
getOptionLabel={(option) =>
typeof option === "string" ? option : option.name
}
disableClearable
inputValue={localInput}
className="!w-full"
onInputChange={onInputChange}
onChange={onChange}
sx={{
"& .MuiAutocomplete-input": {
background: noneBg ? "" : "#ffffff !important",
},
}}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
placeholder={placeholder}
dir="rtl"
InputProps={{
...params.InputProps,
disableUnderline: true,
style: { height: "100%" },
}}
sx={{
background: "transparent !important",
"& .MuiInputBase-input": {
background: "#FAFAFA",
color: "#6C757D",
padding: "0 16px",
fontSize: "14px",
fontFamily: "inherit",
},
}}
className="!shadow-none !w-full !px-5 !h-full !text-[14px] md:!text-[16px] !min-w-[50%] !rounded-0 !font-normal"
/>
)}
/>
);
}
export default AutoComplete;