About Lazy loading Ant Design Components overriding custom CSS

problemsolving, programming, react, selfnote


_Photo by Vlad Tchompalov on _Unsplash

🎵 Note to self...

Upgraded Bunpkg React version to v16.6.x (actually v16.7.0-alpha2 to play around with React Hooks ⚓ as well 😀), which enables support for React.lazy.

But lazy loading Ant Design (AntD, hereafter) components broke the custom CSS imported from the root component using CSS import.

🤔 Problem

Custom CSS styles applied on AntD components were not reflected after deploying the site on Netlify even though it was working in development mode.

Custom styles.css was loaded in the root component. 
And below is the custom CSS in index.js was imported.


And "Step" components (for Wizard) were lazily imported as shown below.


Rendered Step Components

📊 Analysis

The reason for the different way of import was due to Ant Design's babel-plugin-import automatically optimizing CSS/Component imports.

After monitoring the rendered tree & network tab in Chrome devtool, I saw new CSS chunks were being loaded when accessing new Wizard step components.

What I realized is that AntD components had its own CSS-in-JS, thus lazily loading AntD components loaded CSS after my custom CSS in the head, overriding my style in result.

👷 What I did...

I am still researching but can't figure out how to import CSS in React and keep it as the last style loaded.

So the workaround I adopted was to move styles.css to a static file location (public/) and imported it in the body (as CSS-in-JS chunks were loaded in the head).