I am currently building a dropdown based design in React. When I click any one of the buttons, the dropdown appears. Now when I click anywhere inside the dropdown, I want the dropdown to stay. But based on my current implementation, when I click on the dropdown, the dropdown goes away. I can fix this behaviour by prop drilling but the code gets ugly. How can I implement this cleanly?
export default function SearchFilter() {
const [selected, setSelected] = useState(null);
const handleClick = (e) => {
const id = e.target.id;
setSelected(id);
}
};
const clearSelected = (e) => {
if (e.target.id) return;
setSelected(null);
};
useEffect(() => {
window.addEventListener("click", clearSelected);
return () => window.removeEventListener("click", clearSelected);
});
return (
<div onClick={handleClick}>
<MenuItem id={1} className={selected == 1 ? "shadow-xl" : ""}>
<MenuDropdown className={`absolute left-0 top-full translate-y-3 ${
selected != 1 && "hidden" />
</MenuItem>
<MenuItem id={2} className={selected == 2 ? "shadow-xl" : ""} />
<MenuItem id={3} className={selected == 3 ? "shadow-xl" : ""} />
</div>
);
}