DEV Community

Discussion on: CSS-in-JS - styled vs css prop

Collapse
 
geelen profile image
Glen Maddern

Hey Sandrina, so Styled Components was (I think??) the first to really popularize the const Item = styled.div approach, so this is partly my fault, sorry!!

One of the first feature requests for SC was a css style prop just like this which I argued against very strongly at the time, but I don't feel that strongly any more. At the time, that was partly to differentiate ourselves from Glamor (which we were building on top of), which had that feature, but also because SC was designed as a runtime-only library (no Babel transforms allowed, as a deliberate departure from CSS Modules which was tied to Webpack), and you can't really do a css prop without it. Plus, I only wanted one way of doing things, with the argument that if you preferred an alternative use Glamor, or later, Emotion.

But SC has the css prop now so now you can mix-and-match, so honestly, do whatever makes sense to you!

Personally, I really wanted to remove as much as possible from my "markup" section of a React component, so it was just structure and content, e.g.

return (
  <Wrapper>
    <Prompt>What is Delicious?</Prompt>
    <Answer>Pizza!</Answer>
  </Wrapper>
)
Enter fullscreen mode Exit fullscreen mode

This introduces a lot of local names (i.e. local to this file/directory) which I really like, but not everyone does. You're free to define them how & where you like, but I was really going for contextual names over mashing all the markup together.

The polar opposite (which is not what you're suggesting, but it's what I had in mind when I was writing SC), has so much "noise" that I wanted to avoid:

return (
  <div css={{
    display: 'flex',
    alignItems: 'center'
  }}>
    <h2 css={{
      ...typography.h2,
      ...borders.rounded.black
    }}>
       What is Delicious?
    </h2>
    <p css={{
      ...typography.p.grey90.lh14,
      paddingTop: '1rem'
    }}>
      Pizza!
    </p>
  </div>
)
Enter fullscreen mode Exit fullscreen mode

Honestly, your example using <div css={Styles.item}>Pizza</div> is almost as clean, makes the underlying HTML element explicit, and keeps the CSS and the "markup" (structure & content) separate, so I say it looks great, go for it!

Collapse
 
a_sandrina_p profile image
Sandrina Pereira

Thank you so much for this explanation and for being able to explain both sides of the same coin!

Definitely the "polar opposite" is the worse in my opinion. As you said - very noisy.

One last question: When it comes to generating CSS is there any "major" difference between both approaches?