[React] Window.getComputedStyle, useRef를 활용하여 DOM Element의 Style 가져오기

이해용·2023년 8월 15일
0
post-thumbnail

Window.getComputedStyle?

  • getComputedStyle() 메서드는 계산된 CSS 속성과 HTML 요소의 값을 가져옵니다.
  • getComputedStyle() 메서드는 CSSStyleDeclaration 객체를 반환합니다.

Syntax

window.getComputedStyle(element, pseudoElement)

Parameter

ParameterDescription
element필수 사항, 계산된 스타일을 가져올 요소 입니다.
pseudoElement옵션 사항, 가져올 pseudo-element입니다.

Return Value

TypeDescription
An object요소의 모든 CSS 속성 및 값이 포함된 CSSSStyleDeclaration 개체입니다.

Example

const [width, setWidth] = useState<number>();
const [height, setHeight] = useState<number>();

const divRef = useRef<HTMLDivElement>(null);

useEffect(() => {
  if (divRef.current) {
      const divRefStyle = window.getComputedStyle(divRef.current);
      const divWidth = divRefStyle.getPropertyValue("width");
      const divHeight = divRefStyle.getPropertyValue("height");
      setWidth(Number(divWidth.replace(/px/g, "")));
      setHeight(Number(divHeight.replace(/px/g, "")));
    }
  }, []);

return (
      <div className="grid grid-cols-3 gap-4 w-[calc(100%-2rem)] h-[calc(100vh-2rem)] m-4">
        <div
          className="border border-solid border-gray-300 shadow"
          ref={divRef}
        />
        <div className="border border-solid border-gray-300 shadow" />
        <div className="border border-solid border-gray-300 shadow" />
      </div>
  );

위처럼 작성했을 때 divRefStyle을 console.log에 찍어보면 아래와 같이 나타납니다.

이 때, width를 가져오고 싶다면 divRefStyle[”width”] 또는 divRefStyle.getPropertyValue("width")로 가져올 수 있습니다.

const divWidth = divRefStyle.getPropertyValue("width"); // divRefStyle["width"] 도 가능
console.log(divWidth) // 518.125px

결론: Window.getComputedStyle() 메서드를 사용하면 Dom Element의 CSS 속성 값을 필요할 때 가져올 수 있습니다.

reference
https://developer.mozilla.org/ko/docs/Web/API/Window/getComputedStyle
https://velog.io/@stayplz/React-DOM-Element%EC%9D%98-css%EC%A0%95%EB%B3%B4%EB%A5%BC-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0
https://www.w3schools.com/jsref/jsref_getcomputedstyle.asp

profile
프론트엔드 개발자입니다.

0개의 댓글