Override Component Style in React May 2nd 2021 Words: 225

Problem

When developing the web app using a React UI library like AntDesign, it is common to override the style of the components the library provides. The components often use a prop named style to configure its appearance. However, writing in-line style is considered bad coding habit so the style is commonly located in a less or scss file.

The problem is when using modular css, every class name defined in the css file would be compiled to some hash (decided by webpack config), rendering the overriding useless. For example:

1
2
3
4
5
6
7
8
9
10
11
.Comment {
.Content {
.ant-comment-inner {
padding: 0.25rem 0;
}
}
.ant-divider-inner-text {
color: rgba(0, 0, 0, 0.45);
font-size: 0.75rem;
}
}

In the above snippet, .ant-comment-inner and .ant-divider-inner-text couldn’t work because it would be compiled to something like H0TgaEKn_i9-J16MknsUA.

Solution

To tell the css loader to leave the class name alone, use the global selector. For example:

1
2
3
4
5
6
7
8
9
10
11
.Comment {
.Content {
:global(.ant-comment-inner) {
padding: 0.25rem 0;
}
}
:global(.ant-divider-inner-text) {
color: rgba(0, 0, 0, 0.45);
font-size: 0.75rem;
}
}

Although the selector named global, it’s effective only within the curly bracket, so don’t worry it messes the same component in other places.