ant-design / ant-design-icons

⭐ Ant Design SVG Icons
https://ant.design/components/icon/
MIT License
965 stars 584 forks source link

ant-icons do not respect @ant-design/cssinjs layer #660

Open Skysplit opened 4 months ago

Skysplit commented 4 months ago

antd version: 5.19.3 @ant-design/icons version: 5.4.0 @ant-desgin/cssinjs version: 1.21.0

When using ant-icons with cssinjs <StyledProvider layer>, .anticon class has too high specificity and overrides colors for icons for example in <Result status="warning" />

reproduction link: https://codesandbox.io/p/sandbox/antd-layer-zm83kp

In reproduction link: warning icon is black, but it should be orange.

greeze commented 3 days ago

This is definitely a bug that I hope they eventually fix.

In the meantime, I was able to work around this specific problem with some css overrides.

With CSS vars

First, in my theme, I enabled CSS vars:

const ThemeLight: ThemeConfig = {
  cssVar: true,
  components: {...},
  token: {...},
}

Or, if you aren't using a custom theme, you can just put it right in your ConfigProvider:

<StyleProvider layer>
  <ConfigProvider theme={{ cssVar: true }}>
    <MyApp />
  </ConfigProvider>
</StyleProvider>

And then I added the following CSS overrides to my main css file:

[class*='-error'] .anticon {
  color: var(--ant-color-error);
}

[class*='-info'] .anticon {
  color: var(--ant-color-info);
}

[class*='-success'] .anticon {
  color: var(--ant-color-success);
}

[class*='-warning'] .anticon {
  color: var(--ant-color-warning);
}

Without CSS vars

If you don't want to enable CSS vars in your theme, you could also programmatically use the color tokens from your theme:

import { theme } from 'antd'

const AntIconOverrideStyle = () => {
  const { colorError, colorInfo, colorSuccess, colorWarning } = theme.useToken().token

  return (
    <style>
      {`
        [class*='-error'] .anticon {
          color: ${colorError};
        }

        [class*='-info'] .anticon {
          color: ${colorInfo};
        }

        [class*='-success'] .anticon {
          color: ${colorSuccess};
        }

        [class*='-warning'] .anticon {
          color: ${colorWarning};
        }
      `}
    </style>
  )
}

export const MyApp = () => {
  return (
    <>
      <AntIconOverrideStyle />
      ...
    </>
  )
}

This is working for me, at least where those specific colors are concerned. If there are any other conflicts, they can just be added to those styles and they should also work.

This will of course cause issues if there are multiple .anticon elements inside any element with a ...-warning (etc.) class, but you get the idea. Adjust specificity to taste.