Search code examples
javascripthtmlcssreactjsstyled-components

Is it possible to switch the value of a css property using an if statement in styled-components?


I'm trying to display a label that says "required" or "optional" at the end of a tag using the CSS after selector. My idea is to look like this.

enter image description here

I'm using React.js and the styled-components library, so I take props.required as an argument, "required" when {props.required == true}, "required" when {props.required == false} I tried to switch the display, such as "optional".

// form.js
<FormTitle required={true}>Name</FormTitle>
<FormTitle required={false}>Phone Number</FormTitle>


// styles.js
import styled from 'styled-components'
const FormTitle = styled.div`
  ...
  &:after {
    content: ${props => props.required ? "required": "optional"};
    background-color: ${props => props.required ? "#FF0101": "#6FC173"};
    ...
  }
`

But when I do this, the label does not appear.

enter image description here

Apparently, switching the content property of CSS with the if the statement of javascript causes a problem. Because if you don't use an if statement for the content property, everything else works.

  ...
  &:after {
    content: "required";
    background-color: ${props => props.required ? "#FF0101": "#6FC173"};
    ...
  }
`

Is there a way to solve this?


Solution

  • The content property expects the value to be wrapped by quotes. Wrap the expression with standard quotes:

    const FormTitle = styled.div`
      ::after {
        content: '${props => props.required ? "required": "optional"}';
        background-color: ${props => props.required ? "#FF0101": "#6FC173"};
      }
    `
    

    Another option is to use the styled component .attrs() to set a data attribute on the element, and then you use the attribute's value as the content of the pseudo element (::after):

    const FormTitle = styled.div.attrs(props => ({
      'data-required': props.required ? 'required': 'optional',
    }))`
      &::after {
        content: attr(data-required);
        background-color: ${props => props.required ? "#FF0101": "#6FC173"};
      }
    `
    

    Examples - Sandbox