I have a react component that returns another React component similar to shown below:
// Sample Code
import React from 'react';
import Component from "./Component";
import "./styles1.css";
import "./styles2.css";
import "./styles3.css";
export default function Sample(props) {
return <Component />;
}
Two out of the three CSS files come from a NPM package. This component is rendered in other non-react pages. So I call ReactDOM.render on this component wherever I am rendering.
The issues with this approach are:
- Styles in other pages where this component is rendered will cascade into the React component causing the React component to appear not as intended.
- When this component is used to do whatever its intended to do, I call
ReactDOM.unmountComponentAtNode(document.getElementById(idSelector))
. When this happens the styles are still in the<head>
causing other elements in the consuming pages to be distorted.
I have tried the following approaches:
- Using this package react-scoped-css (https://github.com/gaoxiaoliangz/react-scoped-css) along with Webpack that adds a randomly hash to the
<Component/>
causing the CSS to be locally scoped. This won’t solve the cascading styles issue from consuming pages. - Find the style tags by XPath (document.evaluate), and do delete the element from the document. But this will remove styles completely so when I want to render the component again the styles are gone.
It is important to mention that the 2 stylesheets coming from the NPM package are extremely large and minfied so it is not viable change the class names in the Component to use something like CSS Modules, CSS-in-JS or similar approaches. Are there any other approaches that will let me approach this problem without changing the class names? This has been really hard because most of the questions suggest to use CSS modules, CSS-in-JS, etc. for this which will require major re-work of the code.
The Component mentioned here is a extremely large codebase that has a lot of class names (roughly ~10K LOC).