Last active
October 7, 2017 09:43
-
-
Save Purii/c3c6f9b4edd809f86e259f70fcfc6c84 to your computer and use it in GitHub Desktop.
Clean solution to support multiple style schemes on a react (native) component
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 React from 'react'; | |
import { StyleSheet, View } from 'react-native'; | |
// Get colorScheme as prop | |
export default ({ colorScheme }) => ( | |
<View | |
style={ | |
// Check only once instead of n * (amount of available schemes) | |
styles[colorScheme] | |
? styles[colorScheme].container | |
: styles.default.container | |
} | |
/> | |
); | |
const defaultStyles = { | |
container: { | |
width: 50, | |
height: 50, | |
backgroundColor: 'blue', | |
}, | |
}; | |
const styles = { | |
default: StyleSheet.create({ ...defaultStyles }), | |
// Use StyleSheet.create to remain efficiency | |
green: StyleSheet.create({ | |
container: { | |
// Copy the default styles | |
...defaultStyles.container, | |
// Add color scheme specific styles | |
backgroundColor: 'green', | |
}, | |
}), | |
}; | |
// Usage | |
// Blue box | |
<Box /> | |
// Green box | |
<Box colorScheme="green" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment