要素のサイズ変更を監視する
// ── ResizeObserver: 要素のサイズ変更を監視する ────────
// window の resize イベントと違い、特定の要素のサイズ変化を検知できる
const observer = new ResizeObserver((entries) => {
entries.forEach(entry => {
// contentRect: 要素のコンテンツ領域のサイズ
const { width, height } = entry.contentRect;
console.log('サイズが変わった:', width, 'x', height);
});
});
// 監視対象を登録
const box = document.querySelector('.resizable-box')!;
observer.observe(box);
// 監視を停止
observer.unobserve(box); // 特定要素を解除
observer.disconnect(); // 全て解除
// ── React での典型パターン ────────────────────────────
function ResponsiveComponent() {
const ref = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const obs = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
setSize({ width, height }); // サイズをstateに保存
});
if (ref.current) obs.observe(ref.current);
return () => obs.disconnect(); // クリーンアップ
}, []);
return (
<div ref={ref}>
{size.width < 600 ? <MobileLayout /> : <DesktopLayout />}
</div>
);
windowのresizeイベントでは要素単位のサイズ変更を検知できない。グリッドやチャートのレスポンシブ対応に使う。