I'm creating a widget module that will then be assembled into a bundle and connected to the static sites in a single file. One of the main problems is applying the styles of the parent sites to the widget module. Because of this, an attempt was made to encapsulate the widget using the shadow dom.
import React from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';
const StyledButton = styled.button`...`;
function ModuleComponent() {
return (
<div>
<StyledButton>I does not work</StyledButton>
<button style={{ height: 40, color: "red" }}>It works</button>
</div>
);
}
class IncapsulatedReactWidgetElement extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement("div");
this.attachShadow({ mode: "open" }).appendChild(mountPoint);
ReactDOM.render(<ModuleComponent />, mountPoint);
}
}
customElements.define(
"incapsulated-react-widget-element",
IncapsulatedReactWidgetElement
);
function Root() {
return <incapsulated-react-widget-element />;
}
const MOUNT_NODE = document.getElementById("root");
ReactDOM.render(<Root />, MOUNT_NODE);
Actually it works as expected except the styles. I'm trying to use styled components but nothing works expect inline styles. As you can see, I do two render actions: first for integration ModuleComponent into custom element and second - for render the app. In which way styles can get lost?