Home > database >  Next.js: How to get applied styles from element?
Next.js: How to get applied styles from element?

Time:10-21

Let's say I have global.css

.test {
  background-color: black;
  width: 50px;
  height: 50px;
}

For some reason, I need to get the styles data from applied element. I tried refs but it always return empty string.

import { useState, useEffect, useRef } from "react";

const IndexPage = () => {
  const divEl = useRef<HTMLDivElement | null>(null);
  const [divStyle, setDivStyle] = useState({} as CSSStyleDeclaration);

  useEffect(() => {
    if (divEl.current) {
      setDivStyle(divEl.current.style);
    }
  }, [divEl.current]);

  return (
    <div>
      <div ref={divEl} className="test"></div>
      <pre>{JSON.stringify(divStyle, undefined, 2)}</pre>
    </div>
  );
};
export default IndexPage;

Is it because next.js SSR or should I add something to dependency array?

code sandbox here

CodePudding user response:

You can use computed styles to get what you need, although it won't be a "simple" object with properties. You'll need to query each property individually:

if (divEl.current) {
      setDivStyle(getComputedStyle(divEl.current));
    }

and then you can do something like:

divStyle.getPropertyValue("background-color")

Here's an example sandbox (forked from yours) that demostrates it.

  • Related