Combining CSS Modules with Ant Design in ReactJs results in compatibility issues

Struggling to implement CSS Modules for styling in my ReactJs project, I followed the ant design documentation found here: . Unfortunately, it's not working as expected when trying to override the component styles of an ant Button.

Below is a snippet from MyContainer.less file:

 .antButton{
    :global {
        .ant-btn-primary {
            background-color: rgb(215, 226, 233);
          border-color: #848586;
           font-size: 7pt;
            color: red !important;
         }
    }
 }

Code snippet:

import React from 'react';
import { Button } from 'antd';
import 'antd/dist/antd.less';
import styles  from './MyContainer.less';

const MyContainer= () => {
        return (
          <Button type="primary" size="small" className={styles.antButton}  >Download</Button>
    );
 };
export default MyContainer;

Using Ant design (Version 4.3.0) with react (Version 16.13.1) and Webpack (Version 4.42.0). Installed less-loader (Version 7.3.0) and babel-plugin-import (Version 1.13.3).

Unsure if there's a specific Webpack configuration missing or if the issue lies elsewhere?

Answer №1

Finally, I was able to resolve my issue with antd by implementing CSS modules and adding extra configurations for antd styles to work properly. The solution that worked for me can be found on this website: By following the instructions provided on the website and adding the specified configurations in the Webpack.config file under the Rule section, you can successfully use CSS modules and override less styles of antd components.

       {
              test: /\.less$/,
              include: [/src/],
              use: [
                require.resolve('style-loader'),
                {
                  loader: require.resolve('css-loader'),
                  options: {
                    modules: {
                      localIdentName: "[name]__[local]___[hash:base64:5]",
                    },
                    sourceMap: true
                  },
                },
                {
                  loader: require.resolve('less-loader'), // compiles Less to CSS
                  options: { lessOptions:{javascriptEnabled: true }}
                },
              ],
            },
            ... (remaining code follows here)

In addition to these configurations, make sure to add the babel import in your package.json:

    "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react",
      "@babel/preset-typescript"
    ],
    "plugins": [
      [
        "import",
        {
          "libraryName": "antd",
          "libraryDirectory": "lib",
          "style": true
        }
      ]
    ]
  },

Lastly, ensure that you set the style for the wrapper div of antd Components as shown below:

import React from 'react';
import { Button } from 'antd';
//import 'antd/dist/antd.less'; you don't need this line when add babel.
import styles  from './MyContainer.less';

const MyContainer= () => {
        return (
<div className={styles.antButton}>
 <Button type="primary" size="small"  >Download</Button>
</div >
    );
 };
export default MyContainer;

I hope this information proves helpful!

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

Hold off on rendering until the useEffect is complete

Currently configuring the default access level An issue arises when altering the access level within useEffect, leading to the page rendering with the default access level intact. How can I delay the page rendering until useEffect has completed? function ...

The find() method is returning true even though the item is not actually found within the array

What I'm trying to do is develop a simple helper function that can locate dates within an array of dates based on the specified day. In this function, I first convert the name of the day to its corresponding number and then aim to identify all dates m ...

"Upon setting the state in React, the Full Calendar refreshes and retrieves events

My current setup involves using the FullCalendar API to fetch events as shown below: <FullCalendar ref={calendarRef} plugins={[listPlugin, bootstrap5Plugin]} initialView='listMonth' ...

Erase Content Inside the <div> Tag

Currently, I am employing JQUERY and CSS to modify the default content on a website. However, I have encountered the following piece of code: <div id="SortOptions"> Sort by: <select id="SortMain" class="improvedcatalogdropdown"> ...

While HTML and CSS collaborate seamlessly during development, CSS mysteriously disappears when transitioning to production mode

I am brand new to this field and I apologize in advance for any mistakes. Currently, I am working on a node.js project using webpack and HTML loader. To test the project, I am utilizing the dev server dependency to run it locally. All models, views, and te ...

Horizontal image scrolling problem across different browsers

Check out my Fiddle. I'm having trouble with scrolling on different browsers. In Chrome, the scroll behaves as expected and stops when the content ends. However, in Firefox, it keeps scrolling even after reaching the end despite setting a fixed width ...

The children elements inside a parent div with Flexbox are now taking on the height of their container

I am facing an issue with my flexbox grid layout where one column contains a tall image while another column has two shorter images stacked on top of each other. The problem arises when viewing the layout in Internet Explorer, as the height of the smaller ...

How to create fading directional navigation arrows using the Orbit jQuery plugin?

I want the navigation arrows to only appear when the user hovers over the "#featured" div or its display. My current code achieves this, but the transition is quite abrupt: $("#featured, div.slider-nav").hover(function(){ $("div.slider-nav").animate({ ...

React-Bootstrap Popup encounters overlay failure

While using the Tooltip without an OverlayTrigger, I encountered the following error: webpack-internal:///133:33 Warning: Failed prop type: The prop overlay is marked as required in Tooltip, but its value is undefined. The code snippet causing the issu ...

Fluid Centered UL with Bullet Points

We have received a unique request from one of our clients. They are asking for the content within a specific <ul> to be centered along with the icons. Centering and adding icons are doable, but the challenge lies in centering the <li> elements ...

What is the import syntax in React that enables optimized tree shaking?

Which JavaScript import syntax is optimized for tree shaking while maintaining compatibility with older systems? 1. import Button from '@mui/material/Button' import TextField from '@mui/material/TextField' import {Button, TextField ...

What steps are involved in incorporating dynamic pagination in PHP using this particular snippet of code?

I am looking for a way to display a list of numbers from 1 to 1000 in a single line with the ability to scroll. However, I need to exclude both "Prev" and "1" from this list. How can I achieve this? Below is the code snippet that I currently have: echo ...

What causes the content of a sticky navbar to overflow?

I have a situation where my navbar has two styles (.navbar and .navbar_fixed), but the links in the navbar are not fitting properly. I attempted to remove padding and add left: 0;, however, these adjustments did not work as expected. Any suggestions on how ...

The horizontal scrolling with overflow-x is not functioning correctly as it is displaying the scrollbar for the vertical

I am perplexed as to why I am unable to scroll horizontally to view the other pink thumbs. Despite adding an overflow of scroll-x to the thumbs container, which should theoretically allow horizontal scrolling, it only seems to scroll vertically. Could som ...

In TypeScript, the 'as const' syntax results in a syntax error due to the missing semicolon

I incorporated the following code into my react project: export const animation = { WAVES: "waves", PULSE: "pulse", } as const; export type Animation = typeof animation[keyof typeof animation]; Upon running the project, I encounte ...

The most efficient method for interacting with externally generated HTML in Rails

For my Rails page help documentation, I utilized the HelpNDoc help authoring tool to generate a folder containing HTML pages and additional folders for JavaScript, images, stylesheets, and libraries. Now I am seeking the most efficient way to integrate thi ...

Using React with an Array of Promises in Typescript

I have a function that looks like this: function queryProposals(hash:string) { let result = api?.query.backgroundCouncil.proposalOf( hash,(data1:any)=>{ let injectedData = data1.toPrimitive().args.account as InjectedAccou ...

Issues with Linear-Gradient functionality in NativeScript 8 on Android devices

I recently added a linear-gradient to an image in my NativeScript 8 app. Surprisingly, it seems to work perfectly on iOS, but I'm encountering some issues on Android. Despite trying solutions like using -webkit-linear-gradient(), the desired effect is ...

Certain web browsers are experiencing difficulty in scrolling down on the website

We are facing an issue with a recently launched website where it won't scroll in specific browsers. We've observed that users on Mac using Chrome are unable to scroll down the page. Any assistance would be greatly appreciated as we suspect it cou ...

Ways to enhance the header design in a Next.js app using Material-UI in ReactJs

Just built a new react/nextjs app and implemented navigation with Home|account|Jobs. Struggling to figure out how to make the active link bold in the navigation. The code I currently have is not achieving this for me. Utilizing material UI -- Toolbar Ap ...