Last active
June 27, 2018 19:52
-
-
Save mbret/b20b799bd352a36bb831d3d54797bd5b to your computer and use it in GitHub Desktop.
Helper to help deal with StyleSheet in React Native
This file contains hidden or 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
/** | |
* @flow | |
*/ | |
import React, { Component } from 'react' | |
import { StyleSheet, Text } from 'react-native' | |
import { MyCustomText } from './MyCustomText' | |
export class App extends Component { | |
render () { | |
return ( | |
<MyCustomText secondary> | |
My Super App ! | |
</MyCustomText> | |
) | |
} | |
} |
This file contains hidden or 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
export const createStyleSelector = (style) => (name, props = {}) => { | |
let styles = [] | |
Object.keys(style).forEach(key => { | |
let ok = false | |
if (key.startsWith(`${name}.`)) { | |
ok = true | |
key.split('.').forEach(subKey => { | |
// we don't have key | |
if (subKey !== name && props[subKey] !== true) { | |
ok = false | |
} | |
}) | |
} | |
if (ok) { | |
styles.push(style[key]) | |
} | |
}) | |
return [ | |
style[`${name}`] || {} | |
].concat(styles) | |
} |
This file contains hidden or 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
/** | |
* @flow | |
*/ | |
import React, { Component } from 'react' | |
import { StyleSheet, Text } from 'react-native' | |
import { createStyleSelector } from './create-style-selector' | |
export class MyCustomText extends Component { | |
render () { | |
const { | |
primary, | |
disabled | |
} = this.props | |
const style = selectStyle('text', {primary, secondary}) | |
return ( | |
<Text style={style}>{this.props.children}</Text> | |
) | |
} | |
} | |
const styleSheet = StyleSheet.create({ | |
'text': { | |
color: 'black' | |
}, | |
'text.secondary': { | |
color: 'green' | |
}, | |
// this style will only be applied if we have both secondary & disabled props | |
// as true | |
'icon.secondary.disabled': { | |
color: 'green with transparency' | |
}, | |
// icon.disabled use the base color and opacity | |
'icon.disabled': { | |
color: 'black with transparency' | |
}, | |
}) | |
const selectStyle = createStyleSelector(styleSheet) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment