<pattern_check> Is it a good pattern to make HOC with lots of style props?

Viewed 78

I want to write a single HOC which I should be able to use as

export const MyComponent = (props) => <MyView mt5>{props.children}</MyView>

to pass style-related props such as m1, m2, m3 etc.

* MyView,js
import React from 'react'
import { View as RNView, ViewPropTypes, StyleSheet } from 'react-native'
import PropTypes from 'prop-types'

function MyView({ style, ...props }) {
  style = Array.isArray(style) ? style : [style]

  const { m, _m1, _m2, m1, m2, m3, m4, m5, ...rest } = props

  return (
    <RNView
      {...rest}
      style={[
        m && { margin: m },
        _m1 && styles._m1,
        _m2 && styles._m2,
        m1 && styles.m1,
        m2 && styles.m2,
        m3 && styles.m3,
        m4 && styles.m4,
        m5 && styles.m5,

        ...style,
      ]}
    />
  )
}

MyView.propTypes = {
  ...ViewPropTypes,

  _m1: PropTypes.number,
  _m2: PropTypes.number,
  m1: PropTypes.number,
  m2: PropTypes.number,
  m3: PropTypes.number,
  m4: PropTypes.number,
  m5: PropTypes.number,
}

const styles = StyleSheet.create({
  _m1: { margin: 2 },
  _m2: { margin: 4 },
  m1: { margin: 4 },
  m2: { margin: 8 },
  m3: { margin: 12 },
  m3: { margin: 12 },
})

export default View

Question is, is there something wrong with this pattern, anything which I should keep in mind or any way to optimize this approach or some node_module already available for this with react-native support.

1 Answers

I assume you want to pass the styles as props?

Take a look at Styled System, I think it's something similar to what you want to achieve.

Though personally, I prefer the CSS-in-JS approach of styled-components to keep the "actual props" separated for style props. I don't like my "actual props" mixed with the "style props" especially for those with a lot of style props. Browser specific styles rules (-webkit) needs some tweaks when using Styled System too.

Related