skip to Main Content

I have an issue with overriding styles from external components in React. I have a basic component badge which has its own less styles but sometimes I need to apply some styles from an external component (see below).

I have this approach in whole project (lot of components) and I’m trying find solution for this because sometimes it works properly sometimes not. I know that problem with priority of CSS. I know that I can add .badgeItem.badgeItem in external component but as I said it is in whole project and find any solution which solve this issue (maybe a style-loader or something).

badge.tsx

import React from "react";
import styles from "./badge.module.less";
import {cn} from "../../componentUtils";

interface IProps {
    number: number;
    className?: string;
}

export const Badge = (props: IProps) => {
    const {number, className} = props;

    return <div className={cn(styles.badge, className)}>
        {number}
    </div>;
};

badge.module.less

.badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background: red;
  color: white;
  border-radius: 50%;
}

page.tsx

import React from "react";
import styles from "./page.module.less";
import {Badge} from "@/app/components/components/badge/badge";

export const Page = () => {
    return <div>
        <Badge number={456} className={styles.badgeItem} />
    </div>
};

page.module.less

.badgeItem {
  background: yellow;
}

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution. Set webpack: never do codesplitting for css.

    config.optimization.splitChunks.cacheGroups = {
       styles: {
          name: "styles",
          chunks: "all",
          enforce: true
        }
    }
    

    Bad for erformance but fix this issue. And for future never use classname props (never style from external components)


  2. Two ways I know you can go about this is

    1. Use inline-style as this will overwrite the className styles
    export const Badge = (props: IProps) => {
        const {number, className, ...rest} = props;
        return <div className={cn(styles.badge, className)} {...rest}>
            {number}
        </div>;
    };
    
    export const Page = () => {
        return <div>
            <Badge number={456} className={styles.badgeItem} 
              style={{
                background: yellow;
               }}
             />
        </div>
    };
    
    1. Use !important flag in styles.badgeItem
    .badgeItem {
      background: yellow !important;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search