Skip to main content

useResizeObserver

ref를 할당한 타겟 엘리먼트의 DOM 크기 변화를 감지하는 커스텀 훅입니다.


Code

🔗 실제 구현 코드 확인

Interface

typescript
/*
* type ContentRect = {
readonly bottom: number;
readonly height: number;
readonly left: number;
readonly right: number;
readonly top: number;
readonly width: number;
readonly x: number;
readonly y: number;
}
*/
type ContentRect = Omit<DOMRectReadOnly, 'toJSON'>;

const useResizeObserver: <T extends HTMLElement>(
action?: (entry: ResizeObserverEntry) => void
) => {
ref: React.RefObject<T>;
contentRect: ContentRect;
};

Usage

typescript
import React, { forwardRef, useRef } from 'react';
import { useResizeObserver } from '@modern-kit/react';

const Example = () => {
const { ref, contentRect } = useResizeObserver<HTMLDivElement>((entry) => {
console.log('resize', entry);
});

const boxStyle = useMemo(() => {
return {
width: '100%',
height: '400px',
background: '#439966',
fontSize: '2rem',
color: '#fff',
}
}, []);

return (
<div
ref={ref}
style={boxStyle}>
브라우저 너비를 줄여보세요. <br />
{`width: ${contentRect.width}, height: ${contentRect.height}`}
</div>
);
};
브라우저 너비를 줄여보세요.
width: 0, height: 0

Note