Last active
February 15, 2022 08:23
-
-
Save gragland/509efd16c695e7817eb70921c77c8a05 to your computer and use it in GitHub Desktop.
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 | |
); | |
} |
Codesanbox page demo is not working =))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@peniqliotuv done, thanks!