Problem: cannot get ref to update from {current: null} to the actual ref on the component.
What i want to happen: {current: null}, as i understand it, should update to include the div that ref is on in order to be able to click ouside of it (eventually to close it). 9 understand that it does not update on first render, but it does not ever update. It does run twice on page load, both returning current: null.
What i tried: i have followed all the SO advice to use useEffect and then finally separating it into this function which appears to be the most appropriate and up to date method to do this. It just never updates current.
function useOutsideAlerter(ref) {
useEffect(() => {
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
console.log(ref);
} else {
console.log("else", ref);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
}
export const Modal = (props) => {
const [showModal, setShowModal] = useState(props.showModal);
const wrapperRef = useRef(null);
useOutsideAlerter(wrapperRef);
return (
<Layout>
<ModalOuter
showModal={showModal || props.showModal}
id={styles["modalOuter"]}
handleClose={props.handleClose}
>
<ModalInner
ref={wrapperRef}
handleClose={props.handleClose}
>
<Layout display="flex" flexDirection="column">
<Layout display="flex" flexDirection="column">
<ModalTitle title={props.title} />
</Layout>
<HR />
<Layout display="flex" flexDirection="column">
<ModalBody body={props.body} />
</Layout>
</Layout>
</ModalInner>
</ModalOuter>
</Layout>
);
};
ModalInner
export const ModalInner = (props) => {
return (
<Layout
id={props.id}
ref={props.ref}
display="flex"
justifyContent="center"
alignItems="center"
padding="2rem"
margin="2rem"
backgroundColor="white"
>
{props.children}
</Layout>
);
};
Layout Component
export const Layout = (props) => {
return (
<div
id={props.id}
ref={props.ref}
...