Read and consume CSS custom properties (CSS variables) in react.
Wrap your component with withCssVarReader
, and declare which variables you want to read:
const Wrapped = withCssVarReader(
['--my-css-var1', '--my-css-var2', '--my-css-var3', '--unknown-var'],
App
)
This HOC will read these css variables around the wrapped component, and broadcast them with React context.
Inside the wrapped component or any descendant components, use useCssVar
hook to consume css variables:
const [var1, var2, var3, varUnknown] = useCssVar([
'--my-css-var1',
'--my-css-var2',
'--my-css-var3',
'--unknown-var',
])
// or read a single var
const variable = useCssVar('--my-css-var1')
Try it in live demo!