React - How to replace the hover color of an Ant-Design Primary button with a css variable?

13,732

Wrap in :global like so:

:global(.ant-btn-primary) {
  background-color: var(--secondary-color);
  &:hover {
    background-color: var(--secondary-hover-color) !important;
    border-color: var(--secondary-hover-color) !important;
  }
}
Share:
13,732
Jean-Sébastien Viens Morin
Author by

Jean-Sébastien Viens Morin

Updated on June 08, 2022

Comments

  • Jean-Sébastien Viens Morin
    Jean-Sébastien Viens Morin over 1 year

    I'm creating an app with React, Redux, Ant-Design, LESS and many other modules. I have to fetch the Primary color from the DB and I assign it to a CSS variable (--primary-color). I darken the color and assign it to an other CSS variable (--primary-color-darken). I use CSS variables instead of LESS variables because the LESS variables are hardcoded after the compilation and cannot be changed. I succeed to overwrite the AntD css class with my CSS variable, but with hover class it doesn't work. The browser seems to understand the style correctly but compute the wrong one.

    //LESS code
    //Default assigned CSS variables
    :root {
      --primary-color: #EB3052;
      --primary-color-darken: #D62D4C;
      --primary-hover-color: var(--primary-color-darken);
    }
    
    //Default value for Ant-Design
    @primary-color: #EB3052;
    @primary-hover-color: #D62D4C;
    
    //Overwrite the Ant-Design class
    .ant-btn.ant-btn-primary,
    .ant-btn-primary {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
      &:hover {
        background-color: var(--primary-hover-color) !important;
        border-color: var(--primary-hover-color) !important;
      }
    }
    

    I reassign variable inline with a wrapper component that wrap all the app content.

    [other wrapper]
    <div class="CssVariableApplicator" style="--primary-color:#FFFF22;--primary-color-darken:#e6e61f;" data-reactroot="">
      [content]
    </div>
    

    Look at the printscreens for the behavior:

    1. Styled Primary color correctly: https://i.stack.imgur.com/RV057.png

    2. Computed Primary colorcorrectly: https://i.stack.imgur.com/h7967.png

    3. Styled Hover Primary color correctly]: https://i.stack.imgur.com/tSWIN.png

    4. Computed Hover Primary color incorrectly: https://i.stack.imgur.com/Ed4e9.png