1.2.1 • Published 6 years ago
styles-merge v1.2.1
Stylesmerge ·
A declarative JavaScript utility to merge style objects together - developed primarily for React Native styles.
Installation
Install with npm
:
npm install styles-merge --save
Or, if you prefer yarn
:
yarn add styles-merge
After installation, you can import the function as follows:
import stylesmerge from 'styles-merge'
Usage
The stylesmerge
function can be used in two primary ways, conditionally and non-conditionally. In either case, you get the
final 'merged' object by calling .eval()
Conditional usages leverage .ifThen()
and .ifThenElse()
:
import stylesmerge from 'styles-merge'
const styles = stylesmerge()
.ifThen(noOfObjects < 10, { flexDirection: 'row' })
.ifThenElse(isDiscountSeason, { backgroundColor: 'red' }, { backgroundColor: 'green' })
.eval()
Pass an initial set of arguments to stylesmerge()
for non-conditional usage.
import stylesmerge from 'styles-merge'
const styles = stylesmerge(styles.containerStyle, styles.fontStyle)
Furthermore, you can mix and match both the conditional and non-conditional patterns.
React Native Usage
Here's a moderately "real world" dumb component that utilizes this library:
import React from 'react'
import PropTypes from 'prop-types'
import { View } from 'react-native'
import stylesmerge from 'styles-merge'
/**
* Container is a generic element to wrap children
* in a flex View.
*
* @returns {jsx}
*/
const Container = ({ children, centerChildren, flex, style, ...props }) => {
const styles = stylesmerge({ flex })
.ifThen(style !== undefined, style)
.ifThen(centerChildren === true, { alignItems: 'center', justifyContent: 'center' })
.eval()
return <View style={styles}>{children}</View>
}
Container.propTypes = {
children: PropTypes.element.isRequired,
centerChildren: PropTypes.bool,
style: View.propTypes.style,
flex: PropTypes.number
}
Container.defaultProps = {
flex: 1,
centerChildren: false
}
export default Container
License
MIT