[React] DOM Element의 css정보를 가져오기 - (getComputedStyle, useRef)

가만히있으세요·2022년 6월 26일
1
post-thumbnail

📍 0. 문제

React로 Netflix 클론코딩 중 한 element의 margin-left css요소의 값을 가져오고 싶었다.

React에서 렌더링 된 DOM Element의 CSS정보를 어떻게 가져올 수 있을까.



📍 1. 방법

다음과 같은 흐름을 통해 값을 가져오는 방법을 알 수 있었다.

📌 (1). window.getComputedStyle

✅ window.getComputedStyle(element)

MDN Web Docs - window.getComputedStyle()에 의하면,
Window.getComputedStyle() 메소드는 인자로 전달받은 요소의 모든 CSS 속성값을 담은 객체를 회신합니다. 이 속성값들은, 해당 요소에 대하여 활성 스타일시트와 속성값에 대한 기본 연산이 모두 반영된 결과값입니다. 개별 CSS속성 값은 객체를 통해 제공되는 API 또는 CSS 속성 이름을 사용해서 간단히 색인화해서 액세스할 수 있습니다.
참고 : https://developer.mozilla.org/ko/docs/Web/API/Window/getComputedStyle

window.getComputedStyle 을 사용하면 CSS 속성값을 담은 객체를 얻을 수 있다고 한다. 인자로는 element요소를 넘겨주어야한다.

❕인자로 element 요소를 넘겨주어야 하는데, React에서는 element 요소를 어떻게 가져올까.
👉 ‼️‼️‼️‼️‼️ 하단의 📌 (2). useRef() 참고 ‼️‼️‼️‼️‼️‼️

React에서 Css속성값을 얻을 Element를 가져왔다면, window.getComputedStyle를 사용해 Css속성값이 담겨있는 객체를 얻어보자.
코드 :

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

function Test() {
  /* useRef Hook을 통해 ref객체(div1_Ref) 생성*/
  const div1_Ref = useRef();

  useEffect(() => {
    /* ref객체(div1_Ref)의 current를 출력*/
    console.log(div1_Ref.current);
    /* div1_Ref의 모든 CSS 속성 값을 담은 객체 생성*/
    let div1_Ref_style = window.getComputedStyle(div1_Ref.current);
    /* test4 출력 */
    console.log(div1_Ref_style);
  }, []);

  return (
    <div
      className="div1"
      /* ref attribute값을 위에서 생성된 ref객체(div1_Ref)으로 설정  */
      ref={div1_Ref}
      style={{
        backgroundColor: 'white',
        width: '400px',
        height: '400px',
        marginLeft: '100px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <div className="div2" style={{ backgroundColor: 'rgba(0,0,0,0.6)', width: '200px', height: '200px' }}></div>
    </div>
  );
}

export default Test;

출력 :

출력된 객체(div1_Ref_style)를 보면 Css 속성값이 담겨있는 것을 확인할 수 있다.

우리는 이 객체의 .getPropertyValue 메소드를 통해 원하는 CSS속성의 값을 가져올 수 있다.
코드 :

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

function Test() {
  /* useRef Hook을 통해 ref객체(div1_Ref) 생성*/
  const div1_Ref = useRef();

  useEffect(() => {
    /* ref객체(div1_Ref)의 current를 출력*/
    console.log(div1_Ref.current);
    /* div1_Ref의 모든 CSS 속성 값을 담은 객체 생성*/
    let div1_Ref_style = window.getComputedStyle(div1_Ref.current);
    /* test4 출력 */
    console.log(div1_Ref_style);
    /* margin-left 속성 값 가져오기 */
    let div1_Ref_marginLeft = div1_Ref_style.getPropertyValue('margin-left');
    /* test4 출력 */
    console.log(div1_Ref_marginLeft);
  }, []);

  return (
    <div
      className="div1"
      /* ref attribute값을 위에서 생성된 ref객체(div1_Ref)으로 설정  */
      ref={div1_Ref}
      style={{
        backgroundColor: 'white',
        width: '400px',
        height: '400px',
        marginLeft: '100px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <div className="div2" style={{ backgroundColor: 'rgba(0,0,0,0.6)', width: '200px', height: '200px' }}></div>
    </div>
  );
}

export default Test;

출력 :


📌 (2). useRef()

✅ useRef()

Reactjs Docs - useRef()에 의하면,
useRef는 .current 프로퍼티로 전달된 인자(initialValue)로 초기화된 변경 가능한 ref 객체를 반환합니다. 반환된 객체는 컴포넌트의 전 생애주기를 통해 유지될 것입니다...(중략)... 본질적으로 useRef는 .current 프로퍼티에 변경 가능한 값을 담고 있는 “상자”와 같습니다...(중략)... useRef는 내용이 변경될 때 그것을 알려주지는 않는다는 것을 유념하세요. .current 프로퍼티를 변형하는 것이 리렌더링을 발생시키지는 않습니다.
참고 : https://ko.reactjs.org/docs/hooks-reference.html#useref

기존 JavaScript에서 특정 DOM을 선택할 때, getElementById, querySelector와 같은 DOM Selector을 사용해서 DOM 을 선택했다.

React 에서는 useRef() Hook을 사용하여 ref 객체를 생성하고, 선택하려는 DOM Element의 ref attribute 값을 생성된 ref객체로 설정해주면 된다. 그러면 생성된 ref 객체의 .current 값은 우리가 원하는 DOM Element를 가르키게 된다.

코드 :

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

function Test() {
  /* useRef Hook을 통해 ref객체(div1_Ref) 생성*/
  const div1_Ref = useRef();

  useEffect(() => {
    /* ref객체(div1_Ref)의 current를 출력*/
    console.log(div1_Ref.current);
    /* div1_Ref의 모든 CSS 속성 값을 담은 객체 생성*/
  }, []);

  return (
    <div
      className="div1"
      /* ref attribute값을 위에서 생성된 ref객체(div1_Ref)으로 설정  */
      ref={div1_Ref}
      style={{
        backgroundColor: 'white',
        width: '400px',
        height: '400px',
        marginLeft: '100px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <div className="div2" style={{ backgroundColor: 'rgba(0,0,0,0.6)', width: '200px', height: '200px' }}></div>
    </div>
  );
}

export default Test;

콘솔 :



📍 3. 결론

useRef() Hook과, window.getComputedStyle를 사용하여 DOM Element의 css 속성을 가져와보았다.

React Styled-Components를 이용하면 위 과정 없이 손쉽게 가져올 수 있지 않을까 생각해본다.




References

0개의 댓글