DEV Community

Alex Khismatulin
Alex Khismatulin

Posted on

Quick Peek: React App Mounted on a Shadow DOM Root

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);
Enter fullscreen mode Exit fullscreen mode

Play around in playground

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)

Collapse
 
carloscne profile image
Carlos Queiroz

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.

Collapse
 
alexkhismatulin profile image
Alex Khismatulin

Sounds interesting. Glad that you found it helpful!

Collapse
 
lazzy_ms profile image
Maulik

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:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

Any idea why?

Collapse
 
maplemap profile image
Serhiy Illarionov

That's actually what I wanted to found. Thank you!