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 (3)

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
 
maplemap profile image
Sergiy Illarionov

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

Create an Account!
Now it's your turn!
Β 
πŸ—’ Share a tutorial
πŸ€” Reflect on your coding journey
❓ Ask a question

Create an account to join hundreds of thousands of DEV members on their journey.