-
-
Save necolas/5b421ca860ed98eabc5fd2b9bc6d1136 to your computer and use it in GitHub Desktop.
DynamicStyleSheet.js
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 { Appearance, StyleSheet } from 'react-native'; | |
function getTheme() { | |
return Appearance.getColorScheme(; | |
} | |
function getStyles(styles) { | |
return StyleSheet.create(typeof styles === 'function' ? styles(getTheme()) : styles); | |
} | |
/** | |
* Example of | |
* | |
* const styles = StyleSheet.create((theme) => ({ | |
* base: { color: theme.color } | |
* })); | |
*/ | |
const DynamicStyleSheet = { | |
create(styles) { | |
const cache = new Map(); | |
const stylesObject = getStyles(styles); | |
const theme = getTheme(); | |
cache.set(theme, stylesObject); | |
const dynamicStyles = {}; | |
for (let key in stylesObject) { | |
if (Object.prototype.hasOwnProperty.call(stylesObject, key)) { | |
dynamicStyles[key] = { | |
enumerable: true, | |
get() { | |
const theme = getTheme(); | |
if (!cache.has(theme)) { | |
cache.set(theme, getStyles(styles)); | |
} | |
const styleObject = cache.get(theme) || {}; | |
return styleObject[key]; | |
} | |
} | |
} | |
} | |
return dynamicStyles; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment