Search code examples
cssstyled-components

Using Styled Components and passing props to psedo element before not working


I have the follwing styled component, I am trying to pass a prop to it and use it in a pseudo element selector, in this case before. However, it does not work as expected.

However, if I pass the same prop to the background css property or any other property, it works completely fine

Is the following allowed when using styled components?

const Label = styled.label`
  /* This did not work */
  &::before {
    content: ${(props) => (props.field ? "Hi" : "")};
  }
  /*But this works perfectly fine*/
  background: ${(props) => (props.field ? "palevioletred" : "white")};
`;

const Input = styled.input`
  height: 32px;
`;

Solution

  • If you check devtools, you'll see that your CSS rule is making it to the DOM, but it's an invalid value for the content property. It's raw text, with no quotes: Hi. It needs to be "Hi".

    Try doing (notice the backticks for a new template string literal):

    content: ${(props) => (props.field ? `"Hi"` : "")};