Search code examples
reactjsstyled-components

Best way to style a component?


I have two solutions to style my component. Which one is the better choice?

  • First option is to set everything in the styled component.
  • Second option is to use many container and styles one by one containers.

First option:

export const BaseContainer = styled.div`
  span {
    color: #E0E0E0;  
  }
  i {
     margin-right: 16px;
    }
`;
<BaseContainer data-testid="base">
   <i className="icon-share" />
   <span> {base} </span>
</BaseContainer>

Second option:

export const BaseContainer = styled.div`
  color: #E0E0E0; 
`;
export const IconContainer = styled.div`
  margin-right: 16px;
`;
<IconContainer>
  <i className="icon-share" />
</IconContainer>
<BaseContainer data-testid="base">
  {base} 
</BaseContainer>

Solution

  • I would go for the second option as the first option ties together 2 elements in one div and if you would want to use the same css properties in another case would require refactoring.

    But be aware that your second option is not really a small difference from the first:

    • In your first option you have one div with one i and one span inside of it and you are applying style to i and span correspondingly.

    • In your second option you have 2 separate div one with one i and the other with just a content and you are applying style to both div instead.

    That said, the best solution would be to actually style the span and i individually, something like

    const StyledSpan = styled.span`
        color: #E0E0E0;
    `
    
    const StyledIcon = styled.i`
        margin-right: 16px;
    `
    

    And then use them as:

    <div data-testid="base">
      <StyledIcon className="icon-share" />
      <StyledSpan>{base}</StyledSpan>
    </div>