I want to close the dropdown that is currently open when clicked outside of it. I have implemented the logic but I am facing some issues.
I have 5 dropdowns on nav-bar initially everything is working fine the dropdown that is open is closing when clicked outside or when clicked on another dropdown. But after clicking on all the dropdowns the user has to click twice on the dropdown to open, on first click the dropdown that is open is closed, and on the second click dropdown is opening.
I am not able to detect the problem. Below I have given the code for reference.
Dropdown.tsx
function Dropdowns(){
const [showPopup, setShowPopup] = useState({
item1: false,
item2: false,
item3: false,
item4: false,
item5: false,
item6: false,
});
const item1Ref = useRef(null);
const item2Ref = useRef(null);
const item3Ref = useRef(null);
const item4Ref = useRef(null);
const item5Ref = useRef(null);
const item6Ref = useRef(null);
useOutsideClick(item1Ref, () => {
if (showPopup.item1) {
setShowPopup({ ...showPopup, item1: false });
}
});
useOutsideClick(item2Ref, () => {
if (showPopup.item2) {
setShowPopup({ ...showPopup, item2: false });
}
});
useOutsideClick(item3Ref, () => {
if (showPopup.item3) {
setShowPopup({ ...showPopup, item3: false });
}
});
useOutsideClick(item4Ref, () => {
if (showPopup.item4) {
setShowPopup({ ...showPopup, item4: false });
}
});
useOutsideClick(item5Ref, () => {
if (showPopup.item5) {
setShowPopup({ ...showPopup, item5: false });
}
});
useOutsideClick(item6Ref, () => {
if (showPopup.item6) {
setShowPopup({ ...showPopup, item6: false });
}
});
return(
<ul>
<li ref={item1Ref}>
<input type="checkbox" id="item1editcheck" name="item1editcheck" onClick={(e) => {
setShowPopup({ ...showPopup, item1: true });
}} />
<label htmlFor="item1editcheck">Item 1</label>
{showPopup.item1 &&(
<div>My content</div>
)}
</li>
<li ref={item2Ref}>
<input type="checkbox" id="item2editcheck" name="item2editcheck" onClick={(e) => {
setShowPopup({ ...showPopup, item2: true });
}} />
<label htmlFor="item2editcheck">Item 2</label>
{showPopup.item2 &&(
<div>My content</div>
)}
</li>
</ul>
);
}
export default Dropdowns;
useOutsideClick.tsx
import { useEffect } from "react";
const useOutsideClick = (ref: any, callback: any) => {
const handleClick = (e: any) => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
};
useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
export default useOutsideClick;