How to scope styles sheet of a component library to itself by adding unique identifiers while bundling

75 views Asked by At

I have a React project which uses another react library tableRenderer something like that it's a private library. now tableRenderer has its own css file which is not scoped to itself that package doesn't use any cs-in-js library.

if I'm importing that tableRenderer library in my react project. I'm getting css conflicts.

My react project uses tailwind css

SampleCode

React Project

import React from 'React';
import tableRenderer from 'tableRenderer/dist/index';
import 'tableRenderer/dist/styles.css';

function Main(){
  const someStates = useState();
  const tableRef = useRef();

  useEffect(()=> {
    tableRenderer.render(ref,tableData)
  },[])

  return <div>
     <div id='tableRenderer' ref={tableRef}/>
     <div class='otherClasses'> ... </div>  
  </div>
}

for instance, let's take this code to be tableRenderers code

node_modules/tableRenderer/index.js

import React from 'react';
import ReactDOM from 'react-dom';

function App({data}){
  return <div>
    <div class="table"> 
      <div class='columns'> ... </div>
      <div class='rows'> ... </div>
    </div>
  </div>
} 

function tableRenderer(domElement,data) {
  ReactDOM.render(<App data={data} />, domElement);
}

export default tableRenderer;

node_modules/tableRenderer/styles.css

.table{

}
.columns{

}
.rows{

}

Now, I want the tableRenderer library classes to be scoped to itself by adding a unique identifier (some hash values) to its class names when transpiling so that it doesn't conflict with my own react projects css.

like this

node_modules/tableRenderer/index.js

import React from 'react';
import ReactDOM from 'react-dom';

function App({data}){
  return <div>
    <div class="table_uniqueHash"> 
      <div class='columns_uniqueHash'> ... </div>
      <div class='rows_uniqueHash'> ... </div>
    </div>
  </div>
} 

function tableRenderer(domElement,data) {
  ReactDOM.render(<App data={data} />, domElement);
}

export default tableRenderer;

node_modules/tableRenderer/style.css

.table_uniqueHash{

}
.columns_uniqueHash{

}
.rows_uniqueHash{

so is there a way to do this with webpack when transpiling or is there any stratergies?

as my react project uses tailwind we can add prefixes to the tailwind config but our project has grown too large there will be lot of files to change. and we still have custom css which is also used in tableRenderer library

0

There are 0 answers