Valentin Garreau
Valentin Garreau

Reputation: 1063

Best way to style a component?

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

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>

Upvotes: 0

Views: 238

Answers (2)

Marco Daniel
Marco Daniel

Reputation: 5765

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>

Upvotes: 2

pawel
pawel

Reputation: 36965

I think it's a bit opinion based, but I would approach this a manner like this:

const IconContainer = styled.i`
  margin-right:16px;
`;

const Icon = ({ 
    iconType, 
    ...props}) => <IconContainer className={ `icon-${iconType}` } {...props } />;

const BaseContainer = styled.div`
   color: #E0E0E0;
`;

const LabelledIcon = ({ iconType, ...props }) => <BaseContainer>
    <Icon iconType={ iconType } />
   { props.children }
</BaseContainer>;

// usage:
<LabelledIcon iconType="share"> icon label text </LabelledIcon>

Upvotes: 1

Related Questions