Skip to content

Commit 9e49a58

Browse files
committed
Add support for css file style injection to the web component
- Update create method to receive a config object with the properties `useShadowDom` and `cssFile` - Add conditional insertion of link tag to inject a css file to the web component shadow dom
1 parent 0d61d5f commit 9e49a58

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

src/dev/index.js

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ require('@webcomponents/custom-elements');
1010
module.exports = {
1111
/**
1212
* @param {JSX.Element} app
13-
* @param {string} tagName - The name of the web component. Has to be minus "-" delimited.
14-
* @param {boolean} useShadowDom - If the value is set to "true" the web component will use the `shadowDom`. The default value is true.
13+
* @param {string} tagName - The name of the web component. Has to be minus '-' delimited.
14+
* @param {Object} config - The config object used to generate the web component.
15+
* @param {string} config.useShadowDom - If the value is set to 'true' the web component will use the `shadowDom`. The default value is true.
16+
* @param {string} config.cssFile - The css file location in the distribution server. Optional.
1517
*/
16-
create: (app, tagName, useShadowDom = true) => {
18+
create: (app, tagName, config = { useShadowDom: true }) => {
1719
let appInstance;
1820

1921
const lifeCycleHooks = {
@@ -44,7 +46,7 @@ module.exports = {
4446
const webComponentInstance = this;
4547
let mountPoint = webComponentInstance;
4648

47-
if (useShadowDom) {
49+
if (config.useShadowDom) {
4850
// Re-assign the webComponentInstance (this) to the newly created shadowRoot
4951
const shadowRoot = webComponentInstance.attachShadow({ mode: 'open' });
5052
// Re-assign the mountPoint to the newly created "div" element
@@ -63,14 +65,21 @@ module.exports = {
6365
}
6466

6567
ReactDOM.render(React.cloneElement(app, extractAttributes(webComponentInstance)) , mountPoint, function () {
66-
appInstance = this;
68+
appInstance = this;
6769

68-
callConstructorHook(webComponentInstance);
69-
callLifeCycleHook('connectedCallback');
70-
});
70+
callConstructorHook(webComponentInstance);
71+
callLifeCycleHook('connectedCallback');
72+
});
73+
74+
if (config.cssFile) {
75+
mountPoint.insertAdjacentHTML(
76+
'afterbegin',
77+
`<link rel='stylesheet' type='text/css' href='${config.cssFile}'/>`
78+
);
79+
}
7180
}
7281
disconnectedCallback () {
73-
callLifeCycleHook('disconnectedCallback');
82+
callLifeCycleHook('disconnectedCallback');
7483
}
7584
attributeChangedCallback (attributeName, oldValue, newValue, namespace) {
7685
callLifeCycleHook('attributeChangedCallback', [attributeName, oldValue, newValue, namespace]);
@@ -81,5 +90,5 @@ module.exports = {
8190
}
8291

8392
customElements.define(tagName, proto);
84-
},
93+
}
8594
};

0 commit comments

Comments
 (0)