Possible to lift local custom properties to global :root? #4216
Replies: 2 comments
-
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.
-
|
The upcoming release introduces import { createTheme, ThemeProvider } from 'styled-components';
const { theme, GlobalStyles } = createTheme({
colors: { primary: '#007bff', text: '#333' },
spacing: { sm: '8px', md: '16px' },
});
// theme.colors.primary === 'var(--sc-colors-primary, #007bff)'You can test the prerelease: Staged release PR: #5687 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm looking for a solution where I can lift custom css properties up to a global
:rootdefinition. I knowcreateGlobalStyleexists, 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