<aside> 💡 Ref에 대해서 알아보자

</aside>

Ref 객체 생성


import { useRef } from 'react'

const ref = useRef();

useRef 함수를 이용해서 Ref 객체를 만들 수 있다.

ref Prop


const ref = useRef();

<div ref={ref}> ... </div>

ref prop에다가 앞에서 만든 Ref 객체를 내려주면 된다.

DOM 노드 참조하기


const node = ref.current;

if(node){
	// node 를 활용하는 코드
}

Ref 객체의 current 라는 프로퍼티를 사용하면 DOM 노드를 참조할 수 있다.

current 값은 없을 수 있기에 반드시 값이 존재하는지 검사하고 사용해야 하는 주의점이 필요하다.

DOM 노드를 참조하여 이미지 크기를 구하기

img 노드의 크기를 ref 를 활용해서 출력할 수 있다. 이에 대한 예시로

img 노드에 너비 값인 width , 높이 값인 height 라는 속성이 존재하여 Ref 객체의 current 로 DOM 노드를 참조해 속성 값을 가져올 수 있다.

import { useRef } from 'react';

function Image({ src }) {
  const imgRef = useRef();

  const handleSizeClick = () => {
    const imgNode = imgRef.current;

    if (imgNode) {
			const { width, height } = imgNode;
	    console.log(`${width} x ${height}`);
		}
  };

  return (
    <div>
      <img src={src} ref={imgRef} alt="크기를 구할 이미지" />
      <button onClick={handleSizeClick}>크기 구하기</button>
    </div>
  );
}