Ad

Avoiding Duplicate Style Properties When Styling My JSX Content?

- 1 answer

I'm styling some content in React using the inline styles approach. Here is a snippet of what I have:

var textStyles = {
  emphasis: {
    fontSize: 38,
    margin: 0,
    padding: 0,
  },
  smallEmphasis: {
    margin: 0,
    padding: 0
  },
  small: {
    fontSize: 17,
    opacity: 0.5,
    padding: 0,
    margin: 0
  }
}

return(
  <div style={divStyle}>
    <LightningCounter/>
    <h2 style={textStyles.smallEmphasis}>LIGHTNING STRIKES</h2>
    <h2 style={textStyles.emphasis}>WORLDWIDE</h2>
    <p style={textStyles.small}>(since you loaded this example)</p>
  </div>
);

One of the things that bothers me is that I am repeating the properties for margin and padding in my emphasis, smallEmphasis, and small objects. Since cascading isn't possible (AFAIK), is there a clean solution that doesn't involve me duplicating code?

Thanks,
Kirupa

Ad

Answer

If using ES6, this seems like a candidate for the spread operator :

const baseStyle = {
   margin: 0,
   padding: 0
}

const emphasis {
  ...baseStyle,
  fontSize: 38
}

Better yet, in the spirit of DRY, if you find yourself repeating the same baseStyle from component to component, it might be worth separating it out to another file which can then be imported wherever needed:

styles.js

export default {
   margin: 0,
   padding: 0
}

SomeComponent.jsx

 import style from './styles
Ad
source: stackoverflow.com
Ad