The styled components can create identical CSS classes with varying conditions

Below are the CSS styles I am currently using:

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

When I use the Typography component with different variants, the Styled-components library generates the same CSS class for each variant. This results in conflicts between the styles.

Here is an example of how I am using the Typography component with different variations:

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

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

However, despite specifying different variants, the output still displays the same CSS class being applied:

Answer №1

In essence, styled-components generates unique classes where the first class is the same and the subsequent ones are different. This can be observed in the h4 and h3 tags. Would you mind updating #widgetStyles & to #widgetStyles && as shown in the code snippet below?

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you determine the index of a table column in JavaScript when you only know its class name?

I am looking for a way to dynamically hide/show table columns based on their classes, without having to add classes to each individual <td> element. This should be accomplished using classes on the columns themselves. Here is a sample of the table ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

Is there a way to change the background color of product blocks on Shopify in a dynamic

Is there a way to customize the background colors of product blocks on Shopify by modifying the shop code? Take a look at this example: Mockup showing alternating block backgrounds Currently, all product blocks in the grid have a black background with wh ...

Tips on crafting tailored CSS styling for targeted div elements such as before and after:

Looking to style specific div elements with the same class name? <div class="main"> <div class="banner_image"> banner 1</div> <div class="banner_image ">banner 2</div> <div class="banner_image ">banner 3</di ...

globalThis undefined following git hiccup

While working on a web app in React, I followed a certain guide to execute Python code successfully within the app. However, during a git operation, I accidentally added unnecessary files like node_modules and package lock files, which led me to delete ev ...

A flexible approach to updating wrapper tags in React

I need to update the wrapper tag around my content. Currently, I have it set up like this: {!filter && <Styled.DropdownMenu> {Options} </Styled.DropdownMenu>} {filter && <Dropdown.Menu as={CustomMenu}> {Options} < ...

I'm unable to retrieve the information from Sanity. When trying to access the product details, I receive a 404 error

/index file/ i am encountering an issue with fetching data from sanity. Despite validating the slug and schema files, I am getting a "404 page could not be found" error when trying to access the product. Can anyone provide assistance?. import React from ...

What is causing the unexpected impact of the "Product Quick View" JavaScript plugin on divs that are not being activated by user interaction?

As a newcomer to web design, I have implemented the "Product-Quick-View" plugin from CodyHouse on my website. Upon clicking the DEMO button and inspecting the code, you will find the following: <body> <header> <h1>Product Q ...

How can I retrieve new values in MUI's Autocomplete with multiple selection and freesolo enabled?

I have developed an innovative autocomplete feature that allows users to select multiple items, either from a given list or by typing in a new value, similar to how email recipients are managed. All functions are working perfectly - adding items to the lis ...

There seems to be a server issue with the TypeError, as undefined is not iterable and cannot read the property Symbol(Symbol

Encountering the following error message: TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) This issue occurred during the page generation process. Any console logs will be shown in the terminal window. https://i.stack.i ...

How the MUI Grid Component is Creating a Horizontal Scrolling Issue

Title. function DisplayTimes() { const styles = { sectionStyles: { height: 700, backgroundImage: `url(${image})`, backgroundSize: 'cover', backgroundPosition: 'center', ...

The Stripe payment form effortlessly updates in real-time thanks to the powerful @stripe/react-stripejs module

I am experiencing some difficulties with implementing Stripe payment in my Medusa-JS Next JS frontend. Whenever I enter card details in the checkoutForm, the entire StripePayment component keeps re-rendering every time I click on anything within the form ...

Localhost is causing issues with Laravel in retrieving webfonts

I was trying to incorporate font-awesome into my Laravel project, but encountered a strange error. When I run the project, the following error appears in the console: GET http://localhost/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.woff2?5 ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

Tips for making sure the Button component in material-ui consistently gives the same ID value for onClick events

Issue arises when trying to log the ID of the Button component, as it only logs correctly when clicked on the edges of the button (outside the containing class with the button label). This problem is not present in a regular JavaScript button where text is ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...

The functionality of react-infinite-scroll does not seem to be functioning properly when used within

Currently, I am utilizing the react-infinite-scroll-component to paginate comments for a specific post. Within the comment section, there is a button that triggers a drawer to display the paginated comments. However, the issue lies in the fact that the "ne ...

Barely populated React application following setup

I have been diving into React for quite some time now. However, today when I attempted to start a new project, it generated an almost empty project. My usual command create-react-app 'name-of-my-app' was used. It ran for a while and completed th ...

How can you prompt a component again in React Native after a specified number of days have passed?

I am currently working on a component that requests app permissions from the user. This component gives the user the option to either accept the permissions or choose "Later". If the user selects "Later", I want the component to prompt again after specific ...

Managing multiple carousels simultaneously using the middle mouse button in Swiper.js

I am currently utilizing 5 carousels on my screen, all of which are operated by the same navigation buttons. In addition to this, I require the ability to control them using the middle mouse scroll. However, when I activate the mouse wheel control, only ...