The custom CSS classes are being taken over by Antd styles through the use of useServerInsertedHTML in next.navigation

Initially, I encountered a problem where the antd styles on my page were taking 1 to 2 seconds to load, causing my page to render incorrectly during that time. However, thanks to the helpful guidance provided in this answer about the solution to the slow Antd styles loading problem, I was able to resolve this issue.

Now, a new challenge has arisen where the ":where" styles of antd are overriding my custom CSS classes. Despite trying various solutions, I am stuck as I do not want to resort to using "!important" in my CSS for a fix.

While my page now renders perfectly, the issue of styles being overridden persists.

This is just one example of many parts of my site experiencing this issue, as seen in the images below:

https://i.sstatic.net/Y8yse.png

https://i.sstatic.net/BIEuQ.png

In the above images, the ":where" selector of antd is taking precedence over my custom "buttonStyle" styles because it appears before my class styles in the styling hierarchy.

Here is my AntdStyledComponentsRegistry component:

'use client';

import React from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { StyleProvider, createCache, extractStyle } from '@ant-design/cssinjs';

export default function AntdStyledComponentsRegistry({ children }: { children: React.ReactNode }) {
    const [cache] = React.useState(() => createCache()); // gets antd cached styles

    // innsert cache style on the server
    useServerInsertedHTML(() => (
        <style id="antd" dangerouslySetInnerHTML={{ __html: extractStyle(cache, true) }}></style>
    ));

    return <StyleProvider cache={cache}>{children}</StyleProvider>;
}

And here is my main layout.js file:

'use client';
import React, { useEffect, Suspense, lazy } from 'react';
import dynamic from 'next/dynamic';
import { NavBar } from '../../../components';
import AntdStyledComponentsRegistry from "../../utils/AntdStyledComponentsRegistry"
import './dashboardStyle.scss';

const SideBar = dynamic(() => import('../../../components/SideBar'), { ssr: false })

export default function Layout({ children }) {

    return (
        <AntdStyledComponentsRegistry>
            <section>
                <div className="dashboard">
                    <NavBar />
                    <div style={{ display: "flex" }}>
                        <div className="layout-side-bar">
                            <>
                                <SideBar />
                            </>
                        </div>
                        <div>

                            <div className="lower-layout">
                                <div className="layout-side-body">{children}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </AntdStyledComponentsRegistry>
    );
}

Answer №1

If you're looking to customize antd component styles, there are several approaches you can take:

One option is to modify the styles using the token config:

Note: You can view a complete list of props that are customizable for each component here

<ConfigProvider
    theme={{
      token: {
        // primary seed Token
        colorPrimary: '#00b96b',
        borderRadius: 2,

        // Alias Token
        colorBgContainer: '#f6ffed',
        Button: {
          primaryShadow: '0 2px 0 rgb(255, 0, 0)',
          colorPrimary: 'red',
          ... etc...
        } 
      },
    }}
  >
    <Button type="primary">Primary</Button>
  </ConfigProvider>

You can also utilize the style prop for each component:

<Button type="primary"
  style={{
    color: 'red'
  }}
>
  Primary Button
</Button>

Another effective method is to create a custom js/ts file to manage the styles for your components, allowing for better organization:

// 
// component file
//
import Styles from 'path/to/styles.js|ts'

...

function MyComponent() {
  const S = Styles()

...

  return (
    <Button type="primary"
      style={ S.Button }
    >
      Primary Button
    </Button>
  )
}

//
// styles.ts file
//
import { CSSProperties } from 'react'
import { theme as antdTheme } from 'antd'

// types
type StylesType = {
  Button: CSSProperties
  OtherComponent: CSSProperties
}

function Styles(): StylesType {
  const { useToken } = antdTheme
  const { token: theme } = useToken()

  const Button: CSSProperties = {
     color: theme.colorError
  }

  const OtherComponent: CSSProperties = {
    ....
  }

  return {
    Button,
    OtherComponent
  }
}

export default Styles

If you prefer using css, you can override styles using !important or explore methods for increasing specificity as suggested by @CBroe:

increase the specificity of your own rules

I hope this information proves to be helpful for you :)

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

The navigation bar is displaying in the inspect element but is mysteriously invisible on the actual webpage

I am encountering an issue with my website while using react and tailwind. When I inspect the element, it shows that my Navbar is present but does not display visually. There are no errors except for a possible issue with Tailwind CSS. Here is the code sni ...

Is there a way to personalize the title and text of a tooltip within Apexchart?

I am working on creating a scatter plot using Apexchart to demonstrate the correlation between two sets of data. I want to personalize the tooltip in the chart by adding a distinct title for each pair of x and y values. Here is my current JSX setup, where ...

In Internet Explorer, the list items are overlapping, while functioning perfectly in all other web browsers

I've encountered a strange issue with my list item in Internet Explorer. Despite working perfectly in Chrome and other browsers, it fails to function properly in IE. I've built this application using the Vue framework and have faced various probl ...

Is it possible for GraphQL to communicate with an external API?

I am a beginner in the world of GraphQL and have been wondering if I can utilize it to fetch data from an external, third-party API. Currently, I have an express backend and a react frontend set up and I am making a GET request to a third party API to retr ...

How to display images conditionally on the server side using Next.js

I think I may have the answer already, but I thought I'd check if anyone has a different solution. I'm working on a hero banner with one image for mobile and a different one for desktop display. Normally, I would use conditional rendering, but ...

Displaying various components depending on the dropdown choice

Currently, I am developing a dashboard that features a main menu with various options. Once a user picks an option from the menu, they will be directed to a dropdown menu that offers different environments to select from. Based on the chosen environment, t ...

What is the process for incorporating additional fields into Firebase?

I am looking to incorporate a fresh field similar to the example shown below, but I am unsure of how to proceed. In my previous attempt, I utilized a method called {merge: true}, yet encountered no success with resolving the issue at hand. Whenever I inp ...

Guide on integrating web-tree-sitter into a NextJS application

I am eager to create ASTs by parsing code entered on my NextJS web application. After researching, it seems that leveraging web-tree-sitter is the way to go. Following the instructions, I managed to utilize Docker to produce the tree-sitter-javascript.was ...

Utilizing JavaScript to implement an interactive :hover pseudo-class dynamic effect

After reviewing a question on adding a hover class to an element, I am now curious about how to do the opposite. I already have a main class for a button I am planning to create, where I will customize the background for each button using myButton.style.b ...

Integrate database values into your CSS by dynamically changing styles using PHP

I'm attempting to dynamically change my CSS. The CSS value I need is stored in a database table called goals in the order database, which contains id and goal_1. Here's the code snippet I'm working with: <?php $conn = mysqli_connect ...

Acquiring the selected value when the dropdown is modified in a React application

Upon selecting the year 2022, I faced an issue where the logged value did not appear in the console. Strangely, when choosing 2021 instead, '2022' was the value that got printed to the console. To remedy this, I attempted setting the initial stat ...

Issue with disablePortal prop in Mui 5 Autocomplete not functioning as expected

Previously, I was successfully using version 4.11.4 of Mui with the Autocomplete component and had no issues with the disablePortal prop. However, after updating to Mui 5, I noticed that the autocomplete dropdown list sometimes appears at the top instead ...

Tips for resolving issues with the Telegram bot API in Next.js

I've encountered an issue with my Next.js application: the problem seems to be related to a function designed to send data to Telegram using the bot API URL. While this function works flawlessly in a local environment, it fails to function properly wh ...

What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to swit ...

Run a Javascript function two seconds after initiating

My goal is to implement a delay in JavaScript using either setInterval or setTimeout, but I am facing an issue where the primary element is getting removed. Code that works fine without Javascript delay: const selectAllWithAttributeAdStatus = document. ...

When I try to start the editor with HTML content using the convertFromHTML method, I encounter an error stating that

I am encountering an error when trying to initialize my Editor state with a HTML markup. at renderToString (/home/al/Documents/node/admin-next/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27) at render (/home/al/Documents/node/admin ...

What is the best way to distinguish elements in the same HTML using Angular Material?

Currently, I am working on a project using Angular material, where I have a component.html file that defines a form and a table with data. In the first image of my project, you can see the tab title, a form to add new records, and the table displaying exi ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

Levitating with Cascading Style Sheets

Looking for some assistance to troubleshoot my code. I am trying to make the hover color apply only to the navigation bar and not affect the pictures. I attempted to solve this by specifying .a.main-nav:hover { ...}, but it ended up removing the hover effe ...

Whenever I attempt to retrieve an element, the array mysteriously transforms into undefined

Understanding React's Context API In my current project, I am utilizing React's context API to efficiently pass collected data from my API, which is built using Node.js, Express, and MongoDB. One crucial aspect of this setup is the boards array, ...