I have a modal displaying info when an item is clicked. I want to allow the user to close the modal by clicking outside (common behavior). What follows work on codepen but NOT in local (VSC + FF or Chromium).
The JSX part of codepen (local is exactly the same, except last line of course):
const { useState, useEffect, useRef } = React;
const Visu = React.forwardRef(({ text }, ref) => {
return (
<div className="visu" id="visu" ref={ref}>
<h1>{text}</h1>
</div>
);
});
const Item = ({ onClick }) => {
return (
<>
<label
className="blip blipHover"
id="blip"
onClick={onClick}
>
Whatever
</label>
</>
);
};
const App = () => {
const visuRef = useRef(null);
const [showVisu, setShowVisu] = useState(false);
// useEffect(() => {
// manageMouse(document.getElementById("blip"));
// }, []);
useEffect(() => {
console.log("UE showVisu=" + showVisu);
const closeVisu = (e) => {
if (visuRef.current && !visuRef.current.contains(e.target)) {
console.log("closeVisu");
setShowVisu(false);
}
};
if (showVisu)
document.addEventListener("click", closeVisu);
return () => document.removeEventListener("click", closeVisu);
}, [showVisu]);
function manageClick() {
setShowVisu(true);
}
return (
<div id="container">
{showVisu ? (
<Visu
text="Whatever details"
ref={visuRef}
/>
) : null}
<div>
<Item onClick={manageClick} />
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));
The codepen is here: https://codepen.io/YACodepen/pen/BabbEea
What I have noticed:
- in codepen, everything works fine, the component is mounted, UE run (showVisu=false), than the click behaves as expected;
- in local, when the component is mounted, UE run (showVisu=false), but when the item is clicked, the sequence "showVisu=true closeVisu showVisu=false" is triggered! That seems to indicate that the same click that triggers the UE (dependent on showVisu) is not consumed entirely, and used after the click listener is bound to document, which entails the showVisu turning to false, and then the non-appearance of the modal...
Why is there difference in behavior between codepen and the local, and what could be done to get the result?
EDIT: I have found a workaroud: simply replace "click" by "mousedown" for the event bound to document. But I would like to understand what's wrong with 'click'. If anyone has an answer or just even clues... Thanks!