Search code examples
styled-componentsemotion

Styled-Component / Emotion.js Is object-style or template style prefered over another?


I like cleanesss of object-style

const Button = styled.button(
  {
    color: 'darkorchid'
  },
  props => ({
    fontSize: props.fontSize
  })
)

however template(?) style seems to be the main interface that supports more features than object style

const Button = styled.button`
  color: hotpink;
`

Is css-string (template) style prefered (or more featured or supported) over object-style in StyledComponent or Emotion.js ?

  • Edit

For one difference I know I don't think it's possible to do this with object style

const dynamicStyle = props =>
  css`
    color: ${props.color};
  `

const Container = styled.div`
  ${dynamicStyle};
`

Solution

  • Tagged template literals are used much more than objects because the latter was introduced in v3.4. By this time Styled component was already very prominent.

    More than the looks there are no known difference. I personally prefer template literals because that gives the touch and feel of having actual CSS if you use IDE plugins such as vscode-styled-components

    Edited

    here is the code for your edited question:

    const dynamicProps = props => css`
      background: ${props.color};
      font-size: ${props.fontSize};
    `;
    
    const SquareOne = styled.div(
      {
        width: "100px",
        height: "100px",
        background: "blue" // will be overwritten by dynamicProps
      },
      dynamicProps
    );
    

    Sandboxed