Search code examples
javascriptreactjsstyled-components

Conditionally add pseudo-class on hover


I am trying to use styled-components and I need a way to conditionally add a pseudo-class on hover.

Here is an example of my code:

buildRating(numberRating, totalRating) {
  const Star = styled.div`
    display: inline;

    div&:hover:before {
      color: ${Colors.goldColor};
    }
    &:before {
      unicode-bidi: bidi-override;
      direction: ltr;
      content: '\\2605';
      color: ${props =>
        props.hasColorStar ? Colors.goldColor : Colors.blackColor};
    }
  `;

  const ratings = [];
  for (let i = 0; i < totalRating; i++) {
    ratings.push(
      i < numberRating ? <Star key={i} hasColorStar /> : <Star key={i} />,
    );
  }
  return ratings;
}

Now the above styled-component will generate:

/* sc-component-id: sc-iwsKbI */
.sc-iwsKbI {
}
.NnxkP {
  display: inline;
}
div.NnxkP:hover:before {
  color: #f6a128;
}
.NnxkP:before {
  unicode-bidi: bidi-override;
  direction: ltr;
  content: "\2605";
  color: #363636;
}

/* sc-component-id: sc-gZMcBi */
.sc-gZMcBi {
}
.dBzcSQ {
  display: inline;
}
div.dBzcSQ:hover:before {
  color: #f6a128;
}
.dBzcSQ:before {
  unicode-bidi: bidi-override;
  direction: ltr;
  content: "\2605";
  color: #f6a128;
}

I don't want it to generate:

div.dBzcSQ:hover:before {
  color: #f6a128;
}

Is there a way to use the below styled-component

div&:hover:before {
   color: ${Colors.goldColor};
}

when props.hasColorStar is true?

Is there a way of accomplishing this with styled-components?


Solution

  • If you have a props hasColorStar and want to conditional apply the style based on it, you can do something as below:

     const Star = styled.div`
        ...
        ${({ hasColorStar }) => hasColorStar && `
          div&:hover:before {
            color: ${Colors.goldColor};
          }
        `}
        ...
     `;