Skip to content

Commit 79a0b0b

Browse files
authored
Merge pull request #10 from WTW-IM/styled-components-docs
Docs: adding some instructions around Styled Components
2 parents 199559f + 959ad72 commit 79a0b0b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,26 @@ class IncrementerComponent extends ReactHTMLElement {
130130
customElements.define('incrementer', ReactTestComponent);
131131
```
132132

133+
## Styled Components
134+
135+
Using styled-components with ReactHTMLElement seems tricky, but there's actually a very simple way to implement it: the [`StyleSheetManager`](https://styled-components.com/docs/api#stylesheetmanager). An app rendered with `StyleSheetManager` might look like this:
136+
137+
```react
138+
class ReactWebComponent extends ReactHTMLElement {
139+
connectedCallback() {
140+
ReactDOM.render((
141+
<StyleSheetManager target={this.mountPoint.parentNode}>
142+
<App />
143+
</StyleSheetManager>
144+
), this.mountPoint);
145+
}
146+
}
147+
```
148+
149+
We use `this.mountPoint.parentNode` for the styles instead of simply using `this.mountPoint` for the case of unmounting. If stylesheets are a child of `this.mountPoint`, ReactDOM will throw an error when you try to unmount. (`unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.`) This error is a little cryptic, but the bottom line is that ReactDOM expects that everything inside the mounted node was generated by React itself. When we use the same node to place our styles, it breaks that expectation. Using the `parentNode` will cause the styles to be placed within the Shadow DOM, but not inside the same component where our app is mounted.
150+
151+
If you're using a [custom template](#thismountpoint-and-using-custom-templates), you can find a node for your `StyleSheetManager` target by searching through the `shadowRoot` in the same way you might search through `document.body`. Often, simply using `this.mountPoint.parentNode` will still work as expected, even with custom templates.
152+
133153
# Contributing
134154

135155
This package uses `semantic-release`. Changes will be compiled into a changelog and the package versioned, tagged and published automatically.

0 commit comments

Comments
 (0)