Home > Back-end >  Styled component generate same css class with different conditions
Styled component generate same css class with different conditions

Time:07-07

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

CodePudding user response:

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;
          `;
      }
    }}
  }
`;

CodePudding user response:

You can try another approach. Instead switch, create an object with a similar keys. Now we can to separate all custom styles from Typography and place all base styles inside Typography. Now, with props, we can select a key from the object and if we don't have props set the default styles. Also we can use the attrs method to set the className.

Attrs is a chainable method that attaches some props to a styled component. The first and only argument is an object that will be merged into the rest of the component's props. The attrs object accepts the following values Edit dazziling-code

  • Related