Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"` : "")};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading