1

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?

1 Answer 1

1

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};
      }
    `}
    ...
 `;
Sign up to request clarification or add additional context in comments.

3 Comments

Putting a template literal inside a template literal looks very strange and it seems to confuse VSCode with formatting. However, it works!
It does confuse VSCode, however, it's pretty common when it comes to styled-components or other css-in-js library that based on string literal such as emotion. If you want to give it a better format, move the function out of the string literal and assign it to a constant.
Great idea moving it to it's own variable. I'll also check out emotion because i've never heard of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.