Search code examples
antd

Ant Design CSS class list/documents


In MUI for each component there is a section with CSS class list that one can override, I can't find the same for Ant Design, people seem to search in Dev tools inspector but is that the only approach here?


Solution

  • In newest antd versions if you want to overwrite styles by using antd default css classes so yes, you'll need to search for desired class in dev tools, this works but it's not the best sollution.

    You can change component styles in many different ways:

    You can change token config:

    <ConfigProvider
        theme={{
          token: {
            // primary seed Token
            colorPrimary: '#00b96b',
            borderRadius: 2,
    
            // Alias Token
            colorBgContainer: '#f6ffed',
            Button: {
              primaryShadow: '0 2px 0 rgb(255, 0, 0)'
            } 
          },
        }}
      >
        <Button type="primary">Primary</Button>
      </ConfigProvider>
    

    You can use component style prop:

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

    My favorite way is to use a custom js/ts file to handle component styles:

    // 
    // component file
    //
    import Styles from 'path/to/styles.js|ts'
    
    ...
    
    const S = Styles()
    
    ...
    
    <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
    

    Or even use custom css classes:

    // component
    <Button type="primary"
      className={'customStyledButton'}
    >
      Primary Button
    </Button>
    
    // css file
    .customStyledButton {
      // don't forget to add !important so 
      // antd will not overwrite your styles
      color: red !important; 
    }
    

    Hope this helps :)