Skip to content

Commit f938ad2

Browse files
cuberootalexmirea
authored andcommitted
Clean up div after component is unmounted (#12)
1 parent 099f585 commit f938ad2

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

lib/WebComponent.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export class CustomElement extends HTMLElement {
8181
let rootEl = this;
8282
switch(this.constructor.renderRoot) {
8383
case "container":
84-
rootEl = document.createElement("div");
84+
rootEl = this.rootDiv = document.createElement("div");
8585
this.appendChild(rootEl);
8686
break;
8787
case "shadowRoot":
@@ -110,7 +110,11 @@ export class CustomElement extends HTMLElement {
110110
}
111111

112112
disconnectedCallback() {
113-
ReactDOM.unmountComponentAtNode(_rootShadows.get(this));
113+
ReactDOM.unmountComponentAtNode(_rootShadows.get(this));
114+
if (this.rootDiv) {
115+
this.removeChild(this.rootDiv);
116+
delete this.rootDiv;
117+
}
114118
let model = _models.get(this);
115119
if (model) {
116120
model.destroy();

test/WebComponentTest.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,25 @@ describe("WebComponent", () => {
111111
});
112112
});
113113
});
114+
115+
it("should clean up when unmounted", () => {
116+
customElements.whenDefined('custom-component').then(() => {
117+
expect(element.querySelector('div')).to.be.null;
118+
119+
// CustomElement should create a container div
120+
document.body.appendChild(element);
121+
expect(element.querySelector('div')).to.exist;
122+
123+
// CustomElement clean up the container div
124+
document.body.removeChild(element);
125+
expect(element.querySelector('div')).to.be.null;
126+
127+
// Make sure that remounting it works
128+
document.body.appendChild(element);
129+
expect(element.querySelector('div')).to.exist;
130+
131+
document.body.removeChild(element);
132+
expect(element.querySelector('div')).to.be.null;
133+
});
134+
});
114135
});

0 commit comments

Comments
 (0)