Possible to lift local custom properties to global :root? #4216
Replies: 1 comment
-
Maybe this will solve your problem Why
Custom Solution Here's a breakdown of a custom solution to lift local CSS properties to the global 1. Create a custom React hook: import { useEffect, useState } from 'react';
const useGlobalCssVars = () => {
const [cssVars, setCssVars] = useState([]);
useEffect(() => {
const root = document.documentElement;
cssVars.forEach(({ name, value }) => {
root.style.setProperty(name, value);
});
}, [cssVars]);
const addCssVar = (name, value) => {
setCssVars((prevCssVars) => [...prevCssVars, { name, value }]);
};
return { addCssVar };
}; 2. Use the hook in your components: import { useGlobalCssVars } from './useGlobalCssVars'; // Assuming your custom hook is in this file
const MyStyledComp = styled.div`
color: var(--my-css-color-var);
`;
const MyOtherStyledComp = styled.div`
color: var(--my-css-color-var);
`;
const App = () => {
const { addCssVar } = useGlobalCssVars();
useEffect(() => {
addCssVar('--my-css-color-var', 'black');
}, []);
return (
<div>
<MyStyledComp />
<MyOtherStyledComp />
</div>
);
}; How It Works:
|
Beta Was this translation helpful? Give feedback.
-
I'm looking for a solution where I can lift custom css properties up to a global
:root
definition. I knowcreateGlobalStyle
exists, however this is limited to one instance. What I'd like is to be able to define CSS vars locally to my component, but they get extract to a single:root
.e.g.
Beta Was this translation helpful? Give feedback.
All reactions