0

I'm using react to create js widgets that can be added to an external client site. My bundler (webpack) creates js files of my apps that include all styles and assets in the build.

One of the issues that I fear I might face (I haven't yet) is if I have conflicting stylesheets how do I ignore those and explicitly use my own. For instance, I'm using bootstrap for my gird layout, if a client site has a different version of bootstrap than the one in my app how do I make sure only my styles are applied to my widget without disrupting any styles on the client site. Is this even possible?

bos570
  • 1,505
  • 2
  • 23
  • 45
  • You can wrap your styles in something like `#my-super-duper-app { }` and hope that `#my-super-duper-app` is unique across the webs. Also, you can look into [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) – fen1x May 01 '19 at 20:11
  • @fen1x so I'm doing that for my custom styles. Do you think that would work for external styles like bootstrap? – bos570 May 01 '19 at 20:20
  • That certianly _can_ work, but you would have to rewrite all bootstrap styles in your widget to something like `#my-app .col` instead of `.col`, and that is **a lot of work** if you use bootstrap extensively. Personally - I would write my own custom styles instead of depending on external library. – fen1x May 01 '19 at 20:28
  • @fen1x that is the plan, but unfortunately the current app is using bootstrap extensively. I might try and go down the shodow DOM path you mentioned. Thanks! – bos570 May 01 '19 at 20:32

2 Answers2

0

This is what the Shadow DOM is for (as @fen1x already mentioned). If you render your component into a shadow root, parent styles won't be inherited.

The React docs contain a recipe on how to wrap a React component as a Custom Element, so it renders into the shadow root of the latter.

P Varga
  • 19,174
  • 12
  • 70
  • 108
0

Shadow dom does not avoid inheritance of parent styles. Shadow dom makes impossible that css selectors used on the main dom will interfere with the ones from the shadow dom.

See: Shadow Dom inheriting parent page CSS [Chrome] for more info