Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  11] [ 5]  / answers: 1 / hits: 24107  / 7 Years ago, thu, february 16, 2017, 12:00:00

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 using following I get the error.



comp = React.createElement(ReactElem, {
config: config,
onRender: handleRender
});

ReactDOM.render(comp , self.shadowRoot.querySelector('#app1'));


Error



target container is not a dom element


I tried to use content of Web component API but then it gets rendered on top rather inside component. Any leads how can make React component to get rendered inside shadow DOM?


More From » reactjs

 Answers
2

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.
class Example extends React.Component {
onClick() {
console.log('Shadow!')
}
render() {
return(
<div onClick={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);

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js></script>




[#58912] Tuesday, February 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;