i want to make each drop down independent component so if i click on one dropdown only it should open not other but here in this code when i clicking both are open at same time doesnt matter on which i click
interface DropdownProps {
options: string[];
onSelect: (option: string) => void;
}
const Dropdown: React.FC<DropdownProps> = ({ options, onSelect }) => {
const [open, setopen] = useState(false)
const [selected, setselected] = useState<string | null>(null)
const handleClick = (option: string) => {
setselected(option)
onSelect(option);
setopen(false)
}
return (
<div className="dropdown m-1.5 bg-neutral-700 text-neutral-100 w-fit rounded-[0.5rem]">
<button onClick={() => setopen(!open)} className="py-2 px-3">
{selected || "select option"}
</button>
{
open && options.map((option, index) => (
<li className="py-2 px-3 list-none rounded-[0.5rem] hover:bg-neutral-900" key={index} onClick={() => handleClick(option)}>{option}</li>
))
}
</div >
)
}
export default Dropdown
const App = ()=>{
const [selectedOption1, setSelectedOption1] = useState<string | null>(null);
const [selectedOption2, setSelectedOption2] = useState<string | null>(null);
return(
<div className="flex">
<Dropdown options={["Option A", "Option B", "Option C"]} onSelect={setSelectedOption1} />
<Dropdown options={["Option X", "Option Y", "Option Z"]} onSelect={setSelectedOption2} />
</div>
)
}
Actually it's not open, it was your css style make it looks like it opened. Because you put them under the same parent element, and the parent element has display:flex
style, so the children element will keep its height the same as parent, this make it looks like opened. You can remove className="flex"
to see the difference.