타켓을 제외환 타켓의 외부가 클릭 되면,
타켓의 active 상태를 변화시키는 훅
import { useState, useEffect } from 'react';
export const useDetectOutsideClick = (targetRef, initialState) => {
const [isActive, setIsActive] = useState(initialState);
useEffect(() => {
const onClick = ({ target }) => {
if (targetRef.current !== null && !targetRef.current.contains(target)) {
setIsActive(!isActive);
}
};
if (isActive) {
window.addEventListener('click', onClick);
}
return () => {
window.removeEventListener('click', onClick);
};
}, [isActive, targetRef]);
return [isActive, setIsActive];
};