Search code examples
cssreactjsjsxstyled-components

Styled component generate same css class with different conditions


I have these styles:-

import styled, { css } from "styled-components";

const H4 = css`
  font-family: "Futura";
  font-style: normal;
  font-weight: 500;
  font-size: 20px;
  line-height: 140%;
  color: #3a786a;
`;
const H3 = css`
  font-size: 24px;
`;

const Span = css`
  font-size: 16px;
`;

export const Typography = styled.div`
  #widgetStyles & {
    ${(props) => {
      switch (props.variant) {
        case "h4":
          return H4;
        case "h3":
          return H3;
        case "body1":
          return Span;
        default:
          return css`
            font-size: 14px;
            color: #010101;
          `;
      }
    }}
  }
`;

Whenever i tried calling the Typography component with different variations Styled-components generate same css class. Which creates confliction between styles.

This is how i am calling the above defined component with different variations:-

<Typography variant="h4">{label}</Typography>

<Typography variant="h3">{label}</Typography>

But it generates the output with same class:-

output


Solution

  • Basically styled-components generates different classes but the first class is same and other class are different, as you can see in h4 and h3 tag, could you please change #widgetStyles & to #widgetStyles &&, as you can see the below code.

    import styled, { css } from "styled-components";
    
    const H4 = css`
      font-family: "Futura";
      font-style: normal;
      font-weight: 500;
      font-size: 20px;
      line-height: 140%;
      color: #3a786a;
    `;
    const H3 = css`
      font-size: 24px;
    `;
    
    const Span = css`
      font-size: 16px;
    `;
    
    export const Typography = styled.div`
      #widgetStyles && {
        ${(props) => {
          switch (props.variant) {
            case "h4":
              return H4;
            case "h3":
              return H3;
            case "body1":
              return Span;
            default:
              return css`
                font-size: 14px;
                color: #010101;
              `;
          }
        }}
      }
    `;