React Hook recipe from https://usehooks.com/useTheme. Demo: https://codesandbox.io/s/15mko9187
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change the declaration of
key
to aconst