Search code examples
javascriptstyled-components

Styled components interpolation


I am wondering why everybody use styled components like this

export const Title = styled.div`
  margin-top: 48px;
  font-family: ${({ theme }) => theme.font};
  font-size: ${({ theme }) => theme.sizeBig};
  color: ${({ theme }) => theme.dark};
  font-weight: ${({ theme }) => theme.fontWeight}
`

Rather than something like

export const Title = styled.div`
  margin-top: 48px;
  ${({ theme }) => css`
    font-family: ${theme.font};
    font-size: ${theme.sizeBig};
    color: ${theme.dark};
    font-weight: ${theme.fontWeight}
  `}
`

Is there any reason to create arrow function on every line?


Solution

  • Comes down to personal preference. I actually go a little bit further in my apps:

    export const Title = styled.div(({ theme }) => css`
      margin-top: 48px;
      font-family: ${theme.font};
      font-size: ${theme.sizeBig};
      color: ${theme.dark};
      font-weight: ${theme.fontWeight}
    `)
    

    I like it this way since each style is defined in a single template literal.

    Styled Components marks some components as static as an optimisation step, if there's nothing to interpolate. Reading this, it seems like this approach would have no performance impact, since having just one property being interpolated marks the whole styled component as not static.