'getPropertyValue function returns empty string on given DOM element in React TypeScript - How to read CSS vars in React

I've made a simple utility function that should read given CSS variable using getPropertyValue function on :root element.

Code:

export const getCssVariable = (name: string): string => {
  const value = window
    .getComputedStyle(document.documentElement)
    .getPropertyValue(name);

  return value;
};

This works if used in useEffect hook, but outside of it, it returns an empty string.

  1. Why does this happen?
  2. Is there another way to read CSS variables in React? Maybe through custom hook?

Thanks.



Solution 1:[1]

To access DOM elements, and by that also also their css property values, or computedStyle, your react code first needs to be mounted. Writing code in useEffect(() => // your code here, []) ensures that the code is only run after your react code is mounted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthias S