Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active February 15, 2022 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gragland/509efd16c695e7817eb70921c77c8a05 to your computer and use it in GitHub Desktop.
Save gragland/509efd16c695e7817eb70921c77c8a05 to your computer and use it in GitHub Desktop.
import { useLayoutEffect } from 'react';
import './styles.scss'; // -> https://codesandbox.io/s/15mko9187
// Usage
const theme = {
'button-padding': '16px',
'button-font-size': '14px',
'button-border-radius': '4px',
'button-border': 'none',
'button-color': '#FFF',
'button-background': '#6772e5',
'button-hover-border': 'none',
'button-hover-color': '#FFF'
};
function App() {
useTheme(theme);
return (
<div>
<button className="button">Button</button>
</div>
);
}
// Hook
function useTheme(theme) {
useLayoutEffect(
() => {
// Iterate through each value in theme object
for (const key in theme) {
// Update css variables in document's root element
document.documentElement.style.setProperty(`--${key}`, theme[key]);
}
},
[theme] // Only call again if theme object reference changes
);
}
@hieund20
Copy link

Codesanbox page demo is not working =))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment