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>
);
}
I know of a fancy hook for clicking outside of something, will probably help out and I keep seeing it referred to for this, here: https://usehooks.com/useOnClickOutside/
You shouldn't handle the close like that, you can't control where you click with that listener. You should use material ui components because the components have all these functions and many others that you didn't think of right now.
If you want to implement it yourself, you should add a ref to dropdown and create a hook for clicking outside the component.