Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 (var 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
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment