reactjsuse-refline-height

CSSStyleDeclaration not giving any value while using useRef in react


I want to get the line-height of the element in Rect after render and for this I'm using useRef

const titleLineHeight = titletext.current?.style.lineHeight;

and I didn't get any value in CSSStyleDeclaration

enter image description here

Im not sure how to get the values. Please help me

Thanks in advance :)


Solution

  • use getComputedStyle()

    https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

    
    const paraRef = useRef(null);
    
      useEffect(() => {
        const paraStyle = paraRef.current && getComputedStyle(paraRef.current);
        console.log(paraStyle.lineHeight);
      }, []);
    
      return (
        <div className="App">
          <p ref={paraRef}>New text</p>
        </div>
      );