Skip to content

Instantly share code, notes, and snippets.

@Purii
Last active October 7, 2017 09:43
Show Gist options
  • Save Purii/c3c6f9b4edd809f86e259f70fcfc6c84 to your computer and use it in GitHub Desktop.
Save Purii/c3c6f9b4edd809f86e259f70fcfc6c84 to your computer and use it in GitHub Desktop.
Clean solution to support multiple style schemes on a react (native) component
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