const el = useRef();
const [isOpen, setOpen] = useState(false);
const handleCloseModal= e => {
if (isOpen && (!el.current || !el.current.contains(e.target))) setOpen(false);
}
useEffect(() => {
window.addEventListener('click', handleCloseModal);
return () => {
window.removeEventListener('click', handleCloseModal);
};
}, []);
return (
{
isOpen &&
<Modal ref={el}>
...
</Modal >
}
);
window 객체에 target이 ref에 할당한 요소에 포함되어 있으면 click 이벤트가 발생하여 조건에 따라 상태값을 변경하는 콜백 함수를 실행한다.
'공부 > React' 카테고리의 다른 글
React 앱 배포 시 Redux-Saga 로그 출력 안하기 (0) | 2021.01.21 |
---|---|
React 환경변수 사용 방법 (0) | 2021.01.21 |
웹서버(Apache2, Nginx)로 React 배포 시 새로고침 404 에러 해결 (0) | 2021.01.21 |
(React) javascript heap out of memory 오류 해결 (0) | 2021.01.07 |
배열의 index를 key로 사용하면 안되는 이유 (0) | 2020.12.30 |