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

user2645494
  • 111
  • 4

2 Answers2

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.

Vuk
  • 693
  • 4
  • 14
0

try to add !important keyword:

return {
  [`.ant-btn`]: {
    ["&-default"]: {
      backgroundColor: "red !important"
    }
  }
};
Bun Wong
  • 15
  • 2