React Hook recipe from https://usehooks.com/useTheme. Demo: https://codesandbox.io/s/15mko9187
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 | |
); | |
} |
This comment has been minimized.
This comment has been minimized.
@peniqliotuv done, thanks! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Change the declaration of
key
to aconst