Search code examples
reactjsstyled-components

Styled Component Pseudo element not receiving props


I am passing this text prop to this component but the pseudo element doesn't receive the props. I have tested it and it works fine outside of the pseudo element. How would I also pass the props to the pseudo element?

export const OR = styled.span<{ text: string }>`
          align-self: center;
          background-color: #cbd9e2;
          border-radius: 50%;
          position: relative;
          display: inline-block;
          padding: 2.5rem;
          font-weight: 500;
          color: white;
          :before {
            content: ${({ text }) => text};
            text-transform: uppercase;
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translateX(-50%) translateY(-50%);
            transform: translateX(-50%) translateY(-50%);
            font-size: 1.875rem;
          }
        `;

Solution

  • You must add a & sign before such elements with styled components. So:

    export const OR = styled.span<{ text: string }>`
              align-self: center;
              background-color: #cbd9e2;
              border-radius: 50%;
              position: relative;
              display: inline-block;
              padding: 2.5rem;
              font-weight: 500;
              color: white;
              &:before {
                content: ${({ text }) => text};
                text-transform: uppercase;
                position: absolute;
                top: 50%;
                left: 50%;
                -webkit-transform: translateX(-50%) translateY(-50%);
                transform: translateX(-50%) translateY(-50%);
                font-size: 1.875rem;
              }
            `;

    EDIT: based on this github issue, pseudo elements that use content must be written as such:

    // without props
    &::before {
        content: "blah";
    }
    
    
    // with props (please note the quotes that surround the prop
    &::before {
        content: "${p => 'blah'}";
    }

    So in your case, the right syntax might be:

    &::before {
                content: "${({ text }) => text}";
                text-transform: uppercase;
                position: absolute;
                top: 50%;
                left: 50%;
                -webkit-transform: translateX(-50%) translateY(-50%);
                transform: translateX(-50%) translateY(-50%);
                font-size: 1.875rem;
              }