Skip to content

Commit 4df54bf

Browse files
committed
import custom <style> tag to Shadow DOM
this small but powerful addition allows a user of the element to define a custom <style> element inside of the custom element, which is then moved in to the Shadow DOM. The <style> tag can define arbitrary CSS of course, but the main (and supported) way of using it is to override CSS variables to customize the styling of the element. Example: <ge-autocomplete …> <style> :host { --input-bg: salmon; --loading-color: red; } </style> </ge-autocomplete>
1 parent 581c95f commit 4df54bf

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/index.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,22 @@ class GEAutocomplete extends HTMLElement {
130130
}
131131

132132
connectedCallback () {
133+
this.importStyles()
133134
this.render()
134135
}
135136

137+
// importStyles looks for a specific template tag inside the custom element
138+
// and moves its content (expected to be a <style> tag) inside the Shadow DOM,
139+
// which can be used to customize the styling of the component.
140+
importStyles() {
141+
const styles = this.querySelector('style')
142+
if (styles === null) return
143+
144+
// appending the node somewhere else _moves_ automatically it so we don’t have
145+
// to explicitly remove it
146+
this.shadowRoot.appendChild(styles)
147+
}
148+
136149
render () {
137150
ReactDOM.render(
138151
<WebComponent {...this.props} host={this} />,

0 commit comments

Comments
 (0)