Skip to content Skip to sidebar Skip to footer

Shadow Dom And Reactjs

I am using web components in my application. And in a web component, I need to insert a react component. Web Component has Shadow DOM. When I try to render the react component usin

Solution 1:

If you want to insert it inside the shadow DOM of a web component, first select the component (e.g. with querySelector) and then its containing shadow (shadowRoot). Simplified example:

// Create React Element.classExampleextendsReact.Component {
  onClick() {
    console.log('Shadow!')
  }
  render() {
    return(
      <divonClick={this.onClick}>Hello World!</div>
    );
  }
}

// Create web component with target div inside it.const container = document.createElement('app');
document.body.appendChild(container);

// Add shadow root to component.const shadow = document.querySelector('app').attachShadow({ mode: 'open' });

// Select the web component, then the shadowRoot.const target = document.querySelector('app').shadowRoot;

ReactDOM.render(<Example />, target);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Solution 2:

Hey my friend, I took the time and crafted this for us:

// ShadowRoot.jsimportReactfrom"react";

exportclassShadowRootextendsReact.Component {

    attachShadow(host) {
        if (host == null) {
            return;
        }
        host.attachShadow({mode: "open"});
        host.shadowRoot.innerHTML = host.innerHTML;
        host.innerHTML = "";
    }

    render() {
        return (
            <spanref={this.attachShadow}>
                {this.props.children}
            </span>
        );
    }

}

Use it like this:

<ShadowRoot>
    // put stuff here you want inside shadow root
</ShadowRoot>

2 things to consider:

  • the class React.Component is working better than the hook equivalent
  • the innerHTML thing is kinda hacky, and state updates are not working with this component

Post a Comment for "Shadow Dom And Reactjs"