76 lines
2.2 KiB
TypeScript
76 lines
2.2 KiB
TypeScript
/* eslint-disable react-hooks/exhaustive-deps */
|
|
import { useEffect, useState } from "react";
|
|
import ChevronDownIcon from "./icons/ChevronDownIcon";
|
|
import { useClickAway } from "@uidotdev/usehooks";
|
|
import CheckIcon from "./icons/CheckIcon";
|
|
|
|
interface Props {
|
|
required?: boolean;
|
|
defaultOption?: string;
|
|
options: string[];
|
|
onSelect: (option: string) => void;
|
|
}
|
|
|
|
function Select3({ required, defaultOption, options, onSelect }: Props) {
|
|
const [showOptions, setShowOptions] = useState<boolean>(false);
|
|
const [selectedOption, setSelectedOption] = useState<string>();
|
|
|
|
const ref = useClickAway<HTMLDivElement>(() => {
|
|
setShowOptions(false);
|
|
});
|
|
|
|
function handleSelect(option: string) {
|
|
setSelectedOption(option);
|
|
onSelect(option);
|
|
setShowOptions(false);
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!defaultOption) return;
|
|
|
|
handleSelect(defaultOption);
|
|
}, [defaultOption]);
|
|
|
|
return (
|
|
<div ref={ref} className="relative">
|
|
<div
|
|
className="relative flex items-center justify-end"
|
|
onClick={() => setShowOptions((prev) => !prev)}
|
|
>
|
|
<input
|
|
required={required}
|
|
type="text"
|
|
readOnly
|
|
value={selectedOption || defaultOption}
|
|
className="text-sm px-3 py-2.5 h-10 ring-1 ring-inset ring-[#DAE0E5] rounded-lg w-full outline-none pr-8 cursor-pointer"
|
|
/>
|
|
<div className="absolute pr-2 cursor-pointer">
|
|
<div className="w-5 h-5">
|
|
<ChevronDownIcon />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{showOptions && (
|
|
<div className="absolute w-full py-2 mt-2 bg-white rounded-lg shadow">
|
|
{options.map((option, index) => (
|
|
<button
|
|
key={index}
|
|
className="px-4 py-2 hover:bg-[#E6ECF2] transition-colors w-full flex items-center justify-between"
|
|
onClick={() => handleSelect(option)}
|
|
>
|
|
<p className="text-sm">{option}</p>
|
|
{option === selectedOption && (
|
|
<div className="w-5 h-5 text-[#49A1F5]">
|
|
<CheckIcon />
|
|
</div>
|
|
)}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default Select3;
|