Skip to content

Instantly share code, notes, and snippets.

@necolas
Created June 28, 2020 18:27
Show Gist options
  • Save necolas/5b421ca860ed98eabc5fd2b9bc6d1136 to your computer and use it in GitHub Desktop.
Save necolas/5b421ca860ed98eabc5fd2b9bc6d1136 to your computer and use it in GitHub Desktop.
DynamicStyleSheet.js
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