Styling React components inside Web Components

Viewed 86

I'm trying to encapsulate styles & logic of my react component module with using shadow DOM and web components. Everything work as expected except styles. They simply do not apply to DOM nodes. Only inline styles work.

import React from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';

// it won't work
const StyledButton = styled.button`
  width: 300px;
  color: red;
`;

// it will
const inlineStyles = {
  width: 350,
  color: "blue"
}
 
function ModuleComponent() {
  return (
    <div>
      <StyledButton>I does not work</StyledButton>
      <button style={inlineStyles}>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
);

The question: is it even possible to have all this fancy styles like styled components applied to react components which then will be wrapped by shadow DOM?

0 Answers
Related