Overriding styles antd component on V5
Asked Answered
M

2

9

I want to customize the styles of some antd components written in cssinjs.

I created a HOC component to access the theme and override some styles and call it after defining the providers

import { useToken, useStyleRegister } from 'antd/es/theme/internal'
import { prefixCls } from 'Src/constants'
import { ReactNode } from 'react'
import { CSSObject } from '@ant-design/cssinjs'
import { GlobalToken } from 'antd/es/theme/interface'



function getStyleButton(token: GlobalToken): CSSObject {
  return {
    [`.${prefixCls}-btn`]: {
      ['&-default']: {
        backgroundColor: 'transparent '
      }
    }
  }
}



export const OverloadStyle = (props: { children: ReactNode }) => {
  const [theme, token, hashId] = useToken()

  useStyleRegister(
    {
      theme,
      token,
      hashId,
      path: ['OverloadStyle']
    },
    () => [
      getStyleButton(token),
    ]
  )
  return <>{props.children}</>
}

but there was a problem with style priority

order style

calling !important is not the best way

style in head how to make those styles which I define were below? Or are there other more convenient ways to extend the standard styles?

live example enter image description here

Moolah answered 30/1, 2023 at 15:37 Comment(2)
Please add a link of reproduction (stackBlitz, sandBox, etc...).Tripper
@Tripper add exampleMoolah
L
1

Using !important is not a great long-term approach instead ANTD actually has documentation on how to handle this.

Since the release of V5 they have introduced a configuration context provider to allow you to override styles you need to override.

See documentation: https://ant.design/docs/react/customize-theme

Example

<ConfigProvider
    theme={{
      token: {
        colorPrimary: '#00b96b',
      },
    }}
  >
    <Button />
</ConfigProvider>

To find what you need to override each component has a "Design tokens" section which tells you which variable names are used by the component. For example for the collapse you can see here: https://ant.design/components/collapse#design-token.

Finally, you can choose to either wrap each component in its own context provider and override styles locally or you can put the provider at the root of your app and override everything in one place. Each option has some benefits and downsides so you will need to decide based on your needs.

Luane answered 2/8, 2023 at 5:18 Comment(1)
Thank you for your reply. There are no problems with key overrides, everything works fine. The problem is only in overriding css. I have to increase nesting or add !important. I would like to control overrides with the help of the order of initiation of style in html.Moolah
A
0

try to add !important keyword:

return {
  [`.ant-btn`]: {
    ["&-default"]: {
      backgroundColor: "red !important"
    }
  }
};
Alie answered 27/3, 2023 at 17:40 Comment(1)
calling !important is not the best way((Moolah

© 2022 - 2025 — McMap. All rights reserved.