I am stuck in a issue,
I have created one custom table, in each td of table row it has a action button, onclick() of action it open a small menu.
But it never closes the pervious open menu, in-fact open multiple menu.
How to close previous and open only one menu.
Here is the code, which may help you:
import React, { useRef, useEffect, useState } from "react";
export default function App() {
const clickOutside = useRef(null);
const [showHideMenu, setShowHideMenu] = useState(false);
const handleClickOutside = (event, ref) => {
if (ref.current && !ref.current.contains(event.target)) {
if (showHideMenu) setShowHideMenu(!showHideMenu);
}
};
useEffect(() => {
document.addEventListener("mousedown", (event) =>
handleClickOutside(event, clickOutside)
);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
});
return (
<div ref={clickOutside}>
<h1>Hello CodeSandbox</h1>
<button onClick={() => setShowHideMenu(!showHideMenu)}>Show Hide</button>
<button onClick={() => setShowHideMenu(!showHideMenu)}>Show Hide</button>
<button onClick={() => setShowHideMenu(!showHideMenu)}>Show Hide</button>
<div>{showHideMenu ? "show" : "hide"}</div>
</div>
);
}
Actually, this code works as you want. Whenever you click outside of your button, it'll automatically close all other popups.
Here is the code sandbox: