특정 DOM에 접근하기

2023. 12. 27. 10:35React

리액트에서는 재사용성 문제로 요소에서 id 속성을 사용하는 것을 권장하지 않는다. 하지만 기능을 구현하다보면 특정 DOM에 접근해야 할 때도 있다.

 

이럴 때는 Ref를 이용해 특정 DOM에 접근할 수 있다.

 

useRef 훅 사용하기

// useRef 훅 임포트
import { useRef } from 'react';

 

 

아래는 버튼을 클릭하면 canvas에 초록색 네모가 나타나는 예제이다.

export default function RefSample(){
  // ref 선언
  // 현재 ref는 null
  const myRef = useRef(null);
  
  function DoSomethingWithRef(){
    // ref.current를 통해 ref에 저장한 DOM에 접근할 수 있다.
    var ctx = myRef.current.getContext("2d");
    ctx.fillStyle = "green";
    ctx.fillRect(10, 10, 100, 100);
  }

  return(
    <>
      <canvas ref={myRef} width="300" height="300">

      </canvas>
      <button onClick={DoSomethingWithRef}>
        Paint Green!
      </button>
    </>
  )
}

 

 

참고: https://www.javascriptstuff.com/use-refs-not-ids/, https://developer.mozilla.org/ko/docs/Web/HTML/Element/canvas, https://react.dev/learn/manipulating-the-dom-with-refs

'React' 카테고리의 다른 글

State에 배열 저장  (1) 2023.12.03