Styled components best practice | Josh W. Comeau

I'm always interested to see how other people utilise styled-components and the tips Josh shares offer exactly that kind of insight. I fundamentally disagree with his take on descendent selectors (👀) but really love his use of CSS variables as a passthrough technique. Prop passthrough to CSS is something that I always have to think about with styled-components, but this feels like a very performant and useful mental model:

function Backdrop({ opacity, color, children }) {
  return (
    <Wrapper
      style={{
        '--color': color,
        '--opacity': opacity,
      }}
    >
      {children}
    </Wrapper>
  )
}

const Wrapper = styled.div`
  opacity: var(--opacity);
  background-color: var(--color);
`;

It feels like this method fits the spirit of both CSS and styled-components much better than techniques I've used in the past 👍

Still, even Josh doesn't have any tips on how to get rid of styled-components most opinionated (and, imo, most annoying) feature: class-name hashes. He does mention the excellent method of at least prepending the meaningless gibberish with a useful, human-readable token, but I still wish you could go a step further and just define the class name yourself. One of these days...

Explore Other Notes

⬅ Newer

How to use tabindex

Great overview on when/when not to use the tabindex attribute. Most of it feels like common sense, but the recommendation for overflow content is an interesting one I'd not come across […]
  • I'm always interested to see how other people utilise styled-components and the tips Josh shares offer exactly that kind of insight. I fundamentally disagree with his take on descendent selectors [&#8230;]
  • Murray Adcock.
Journal permalink

Made By Me, But Made Possible By:

CMS:

Build: Gatsby

Deployment: GitHub

Hosting: Netlify

Connect With Me:

Twitter Twitter

Instagram Instragram

500px 500px

GitHub GitHub

Keep Up To Date:

All Posts RSS feed.

Articles RSS feed.

Journal RSS feed.

Notes RSS feed.