3

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

1 Answer 1

5

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;
          `;
      }
    }}
  }
`;
Sign up to request clarification or add additional context in comments.

3 Comments

nice, good to know. But i can't remove the id as this is needed. This whole thing is a widget and we are wrapping all styles under the #Id widgetStyles so that it wont effect the other styles on the page where it'll be integrated.
Hi @JA9 I have updated the answer, could you please try.
nice, this is working now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.