Skip to content

Styled Components Naming Convention

I was messing around with styled-components in React, and I was struck by how awful the standard naming convention is:

import styled from "styled-components";

const StyledCard = styled.div`...`;
const StyledImage = styled.img`...`;
const StyledDescription = styled.div`...`;
const StyledCTA = styled.a`...`;

export const Card = () => (
    <StyledImage />
    <StyledDescription />
    <StyledCTA />

Since these sub-components are all scoped to this component, my inclination is to name them as they are:

const Card = styled.div`...`;
const Image = styled.img`...`;
const Description = styled.div`...`;
const CTA = styled.a`...`;

However this won't work as the Card styled component can't share the same name as the Card exported compound component.

export const Card = () => (
  <Card /> // yo dawg, I heard you like cards

I did a small amount of searching for better styled-components naming conventions, and came across an article that suggested namespaces.

export const Card = () => (
    <S.Image />
    <S.Description />
    <S.CTA />

I'm not overly sold on namespaces as they come with trade-offs that can make them awkward to set up properly…

…but it did remind me a bit of classic jQuery syntax.

And since we're in the React world of scoped modules with no need of jQuery it gave me the idea to repurpose $ for styled components:

import $ from "styled-components";

const $Card = $.div`...`;
const $Image = $.img`...`;
const $Description = $.div`...`;
const $CTA = $.a`...`;

export const Card = () => (
    <$Image />
    <$Description />
    <$CTA />

Honestly, I kinda like it. It helps to differentiate the internally scoped components from externally scoped components, and apart from needing to remind people that $ is not jQuery I don't see any significant issues. Even nicer is the "S" in the dollar sign can actually symbolically represent "Styled".