Skip to content

Instantly share code, notes, and snippets.

@lgraubner
Last active January 30, 2019 09:34
Show Gist options
  • Save lgraubner/4b78a7a6af7f29fc6f5230e1f3a70f65 to your computer and use it in GitHub Desktop.
Save lgraubner/4b78a7a6af7f29fc6f5230e1f3a70f65 to your computer and use it in GitHub Desktop.
A little helper function to add variant styles to a React component.
const Button = ({ onPress, variant }) => {
const applyVariantStyle = variantStyleFactory(variant)
return (
<TouchableScale
style={[
styles.button,
applyVariantStyle({
small: styles.buttonSmall,
big: styles.buttonBig
})
]}
onPress={onPress}
>
<Text>
{children}
</Text>
</TouchableScale>
)
}
const Button = ({ onPress, variant }) => (
<TouchableScale
style={[
styles.button,
variant === 'small' ? styles.buttonSmall : {},
variant === 'big' ? styles.buttonBig : {}
]}
onPress={onPress}
>
<Text>
{children}
</Text>
</TouchableScale>
)
/**
* Style helper function for variant styles. Removes
* clutter and repetitive conditionals inside style
* objects. Especially shines when having to add variant
* styles to more than one child.
*
* Example:
*
* const applyVariantStyle = variantStyleFactory('small')
*
* const style = applyVariantStyle({
* small: { fontSize: 12 },
* big: { fontSize: 24 }
* })
*
* => { fontSize: 12 }
*/
export default variant => (styles = {}) => variant && styles[variant] ? styles[variant] : {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment