Code first
import React, { FC } from "react";
import { render } from "react-dom";
const App = () => <div>React + Shadow DOM</div>;
const root = document.querySelector("#react-root");
root.attachShadow({ mode: "open" });
render(<App />, root.shadowRoot);
What's this all about?
The code above is very similar to the way we usually mount React apps to the DOM. But there's one significant difference: we're creating a shadow DOM and mounting to its root a React app. Learn more about shadow DOM.
Use-cases
- Isolate styles: an app will not be affected by any outer CSS that brings a good solution when you need styles isolation
- WEB components: React apps can be mounted inside WEB components
Cons
- Styles need to be stored in the shadow root
- You might have issues with external libraries that access DOM elements inside an app through JS
- Some payment processors don't support shadow DOM in the official clients
In the end
This definitely is not something that should be used on a daily basis but it's a good option when you need to implement behavior mentioned in use-cases.
I tried to make this post really short so feel free to ask any questions in the comments.
Thanks for reading!
P.S.
I started doing Twitter recently so I would be glad if you check the things I post there! Also, advise who in your opinion I need to follow from the tech!
Twitter
Top comments (4)
Interesting.
I'm working on a project here that using React inside Magento but in a different way. Magento is importing only JS and CSS files and inject them directly into HTML.
Said that we are facing CSS issues, due to Magento has his own CSS styles.
Maybe this implementation could help me. I'll try it.
Sounds interesting. Glad that you found it helpful!
Working on an external widget script, where the widget is built with react and tailwind css, faced the problem of css encapsulation as the target site also uses tailwind css. Tried the shadow dom approach but getting this error and the widget is not loading:
Any idea why?
That's actually what I wanted to found. Thank you!