Files
frontend/apps/wr/components/ui/searchInput/searchInput.tsx
T

112 lines
3.4 KiB
TypeScript

import { Input } from "@common/components/ui";
import React, { useCallback, useEffect, useRef, useState } from "react";
type SearchType = {
searchNm: string;
searchPk: string;
};
type thisProps = {
label: string | undefined;
initValue: string | undefined;
setValue: (searchNm?: string) => void;
setRtnData: (rtnData: any) => void;
searchList?: any[];
readonly?:boolean
};
export default function SearchInputText({
label = undefined,
initValue = undefined,
setValue = () => {},
setRtnData = () => {},
searchList = undefined,
readonly = false, // 추가: readonly prop
}: thisProps) {
const [isOpen, setIsOpen] = useState(false);
const [textValue, setTextValue] = useState(initValue || "");
const wrapperRef = useRef<HTMLDivElement>(null);
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setTextValue(value);
setValue(value);
if (value) {
setIsOpen(true);
} else {
setIsOpen(false);
}
},
[setValue]
);
const handleSuggestionClick = useCallback(
(dmdCoNm: string) => {
setTextValue(dmdCoNm);
setValue(dmdCoNm);
setIsOpen(false);
setRtnData(searchList?.find((item) => item.dmdCoNm === dmdCoNm) || {});
},
[searchList, setRtnData, setValue]
);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
wrapperRef.current &&
!wrapperRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
return (
<div ref={wrapperRef}>
<Input
type="text"
value={textValue}
onChange={handleInputChange}
/* onFocus={() => setIsOpen(true)} */
className="w-full h-[3.2rem] !text-xl pl-3 text-gray-600 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={`${label}을(를) 입력하세요`}
readOnly={readonly} // readonly 상태 적용
/>
{isOpen && (
<div className=" z-1 w-full mt-2 bg-white border border-gray-300 rounded-md shadow-lg h-90 overflow-auto">
<div className="max-h-72">
{searchList && searchList.length > 0 ? (
searchList.map((item: SearchType, index: number) => (
<div
key={index}
className="!text-xl w-full text-left px-5 py-3 hover:bg-gray-100 cursor-pointer overflow-auto"
onClick={() => handleSuggestionClick(item.searchNm)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
handleSuggestionClick(item.searchNm);
}
}}
>
{item.searchPk?.substring(0, 10)}&nbsp;
<span className="float-right">{item.searchNm}</span>
</div>
))
) : (
<div className="!text-xl w-full px-5 py-3 hover:bg-gray-100 cursor-pointer overflow-auto">
검색 결과가 없습니다.
</div>
)}
</div>
</div>
)}
</div>
);
}