1

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 an 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:

  1. Styles in other pages where this component is rendered will cascade into the React component causing the React component to appear not as intended.
  2. 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:

  1. 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.

  2. 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.

  3. Using shadowDOM in the consuming pages with a div -> shadow host -> shadow root -> react-app root. Styles are properly encapsulated but click events are giving issues.

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).

shashank
  • 21
  • 3
  • I have referred to this one. These either require changing the CSS to CSS Modules (requires changing class names), CSS-in-JS (not feasible with minified CSS), BEM (requires major rework to change class names in CSS and in the code). I have tried the other solution like react-scoped-css but that doesn't work. – shashank Jan 24 '22 at 15:17

0 Answers0