useClickAway
특정 요소 외부의 클릭을 감지하는 Hook입니다. 모달, 드롭다운 메뉴 등 외부 클릭 시 닫아야 하는 UI 컴포넌트에 유용합니다.
Return
ref
: 클릭 감지를 제외할 요소에 연결할 ref 객체
Props
이름 | 타입 | 설명 |
---|---|---|
callback | () => void | 요소 외부가 클릭될 때 호출되는 콜백 함수 |
Usage
import { useClickAway } from '@teamsparta/react';
function Example() {
const ref = useClickAway(() => {
console.log('외부가 클릭되었습니다!');
});
return <div ref={ref}>이 영역 외부를 클릭하면 콜백이 실행됩니다</div>;
}
Example
모달 닫기
function Modal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
const modalRef = useClickAway(onClose);
if (!isOpen) return null;
return (
<div className="modal-overlay">
<div ref={modalRef} className="modal-content">
<h2>모달 내용</h2>
<p>모달 외부를 클릭하면 닫힙니다.</p>
</div>
</div>
);
}