I'm trying to add dark mode support to my React Native app. I will have a flag in a mobx store mode
which will be light
or dark
as appropriate.
In order to tie this into an existing app, I wanted to, if possible, keep the existing style definitions and only override when needed (rather than rewrite everything to a light and a dark theme).
I came up with a function like the following to return the appropriate styles based on the current mode:
function getStyle(style) {
let ret = [styles[style]];
if (
styles.hasOwnProperty(Store.mode) &&
styles[Store.mode][style] !== "undefined"
) {
ret.push(styles[Store.mode][style]);
}
return ret;
}
The view would be rendered as such:
...
<View style={getStyle("container")}>
<Text style={getStyle("text")}>Some text</Text>
</View>
...
The styles:
const styles = {
dark: {
container: {
backgroundColor: "#000"
},
text: {
color: "#fff"
}
},
container: {
padding: 20,
backgroundColor: "#fff"
},
text: {
fontSize: 18,
color: "#000"
}
};
Now this works, but I'm not sure if it's coming at some performance cost I'm unaware of right now (the use of the function, using a style object instead of StyleSheet.create
...), or if there's a much simpler way I can't see for the trees. I'd rather not do a ternary inline on every element either.