From 24ee78abaf6f4dfbebf618b03c058a178f216de4 Mon Sep 17 00:00:00 2001 From: Stephen Cook Date: Wed, 13 Feb 2019 18:50:03 +0000 Subject: [PATCH] Make the shadow root optional --- README.md | 12 ++++++++++++ src/reactive-elements.js | 17 +++++++++++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6de9e65..e877990 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,18 @@ Subscribing to DOM events is similar: React.findDOMNode(this).addEventListener('change', function(e){...}); ``` +## Options + +You can also specify options to the `ReactiveElements` call, e.g. + +```js +ReactiveElements('welcome-component', Welcome, options); +``` + +### `options.useShadowDom` _(default `false`)_ + +By default, your React element is rendered directly into the web-component root. However, by setting this option - your React element will instead be rendered in a [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) inside the web-component instead. + ## Dependencies - [React.js](https://github.com/facebook/react) diff --git a/src/reactive-elements.js b/src/reactive-elements.js index 4ad5bd6..f152f3c 100644 --- a/src/reactive-elements.js +++ b/src/reactive-elements.js @@ -2,11 +2,20 @@ import * as utils from './utils'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; +const getRenderRoot = (element, useShadowDom) => + useShadowDom ? element.shadowRoot : element; + function reactiveElements(elementName, ReactComponent, options) { + const { useShadowDom = false } = options; + function create(parent, props) { var element = React.createElement(ReactComponent, props); parent.reactiveElement = element; - return ReactDOM.render(element, parent.shadowRoot, props.onRender); + return ReactDOM.render( + element, + getRenderRoot(parent, useShadowDom), + props.onRender + ); } function exposeDefaultMethods(reactComponent, customElement) { @@ -21,10 +30,10 @@ function reactiveElements(elementName, ReactComponent, options) { constructor() { const self = super(); - self.attachShadow({ mode: 'open' }); + if (useShadowDom) self.attachShadow({ mode: 'open' }); const observer = new MutationObserver(() => { - ReactDOM.unmountComponentAtNode(self.shadowRoot); + ReactDOM.unmountComponentAtNode(getRenderRoot(self, useShadowDom)); const props = utils.getProps(self); props.children = utils.getChildren(self); create(self, props); @@ -61,7 +70,7 @@ function reactiveElements(elementName, ReactComponent, options) { } disconnectedCallback() { - ReactDOM.unmountComponentAtNode(this.shadowRoot); + ReactDOM.unmountComponentAtNode(getRenderRoot(this, useShadowDom)); } }