프레임워크/React(NextJs)
[React] React 특정 Element영역 내의 마우스 위치 값 구하기
릴리코더
2024. 8. 7. 10:22
프로젝트 내에서 Custom Context Menu 를 사용할 일이 있었는데,
특정 Element에서만 동작해야 했다.
아래 코드는 마우스 이벤트 객체와 Ref Element 객체로 좌표를 구하는 함수이다.
export const getAbsoluteAnchorPoint = (
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
ref: React.RefObject<HTMLElement>,
) => {
const refRect = ref.current?.getBoundingClientRect();
const wrapperScrollY = ref.current?.scrollTop ?? 0;
const rectTop = refRect?.top ?? 0;
const wrapperScrollX = ref.current?.scrollLeft ?? 0;
const rectLeft = refRect?.left ?? 0;
const x = e.clientX - rectLeft + wrapperScrollX;
const y = e.clientY - rectTop + wrapperScrollY;
return { x: x, y: y };
};
위와 같이 함수를 만들어 두고, 아래와 같이 적용해서 사용했다.
const TestPage = () => {
// ...
const wrapperRef = useRef<HTMLDivElement>(null);
const [anchorPosition, setAnchorPosition] = useState({ x: 0, y: 0 });
const contextMenuHandler = (e) => {
e.preventDefault(); // 기본 동작을 막음
const { x, y } = getAbsoluteAnchorPoint(e, wrapperRef);
setAnchorPosition({ x, y });
}
return (
<>
<div ref={wrapperRef} onContextMenu={contextMenuHandler}
<div id='contents'></div>
<div id='contextMenu' style={{ top: anchorPosition.y, left: anchorPosition.x }}>
<ul>
<li>메뉴1</li>
<li>메뉴2</li>
<li>메뉴3</li>
</ul>
</div>
</div>
</>
)
}
export default TestPage;