On button click I want the Modal to appear.
The Modal component adds a eventListener so it closes when you click outside the modal. In React 18 the click event triggers because the button click that happend before Modal was rendered? If I change to react 17 this does not happen.
Find a CodeSandbox here. Notice,
when you click the button the show state sets to true.
Then the Modal component renders and calls the close function directly.
App.js:
import { useState } from "react";
import Modal from "./Modal";
import "./styles.css";
export default function App() {
const [show, setShow] = useState(false);
const close = () => {
setShow(false);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button
onClick={(e) => {
setShow(true);
}}
>
Click
</button>
{show && <Modal close={close} />}
</div>
);
}
Modal.js
import "./styles.css";
import { useRef, useEffect } from "react";
export default function Modal({ close }) {
const ref = useRef(null);
useEffect(() => {
const handleOutsideClick = (e) => {
if (!ref?.current?.contains(e.target)) {
console.log("This one gets called because of the button click", e);
close();
}
};
document.addEventListener("click", handleOutsideClick, false);
return () => {
document.removeEventListener("click", handleOutsideClick, false);
};
}, [close]);
return (
<div ref={ref} className="Modal">
<h1>I'm a Modal!</h1>
</div>
);
}