[리액트] 컴포넌트 사이즈 참조 - useRef사용

bunny.log·2022년 10월 5일
0

예제 1 )

if (ImageBoxRef.current !== null) {
	const width = ImageBoxRef.current.offsetWidth;
	const height = ImageBoxRef.current.offsetHeight;
}

예제 2 )

import React, { useEffect, useRef, useState } from 'react';

const SizeRefComponent = () => {
  const containerRef = useRef(null);
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const handleResize = () => {
      // 참조한 엘리먼트(containerRef.current)의 크기를 가져와서 상태를 업데이트합니다.
      if (containerRef.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        setContainerSize({ width, height });
      }
    };

    // 컴포넌트가 마운트될 때와 창 크기가 조절될 때 리사이즈 이벤트 리스너를 추가합니다.
    handleResize(); // 초기 크기 설정
    window.addEventListener('resize', handleResize);

    // 컴포넌트가 언마운트되거나 업데이트되기 전에 리스너를 제거합니다.
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // useEffect의 두 번째 인자에 빈 배열을 전달하여 최초 렌더링 시에만 실행되도록 설정

  return (
    <div>
      <div ref={containerRef} style={{ width: '100%', height: '300px', background: 'lightblue' }}>
        {/* 크기를 참조하고자 하는 컨테이너 엘리먼트 */}
      </div>
      <p>Container Width: {containerSize.width}px</p>
      <p>Container Height: {containerSize.height}px</p>
    </div>
  );
};

export default SizeRefComponent;
profile
나를 위한 경험기록

0개의 댓글