this.children gets overwritten by Tonic changes
When using this.children inside a Tonic component, I thought it would refer to the original elements that were inside the component HTML when it was first created. This is true when the component starts. However, once it's been rendered, the new rendered content is now written into this.children and the original content is lost. Can that original content be retrieved somehow? this.children is an HTMLCollection, so I can't simply save a reference to it in willConnect() (because it is a NodeList and so is dynamically updated) and if I make an array from it (this.state.savedChildren = Array.from(this.children) in willConnect()) Tonic doesn't like me passing it an Array to render in this.html (stored elements seem to toString() as something like placehold:tonic0:tonic1__.)
An example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<click-to-show id="c">
<p>I am a child of the click-to-show component!</p>
<p>So am I!</p>
</click-to-show>
<script type="module">
/*jshint esversion: 10 */
import Tonic from "./node_modules/@optoolco/tonic/index.esm.js";
class ClickToShow extends Tonic {
click (e) {
if (e.target.nodeName.toLowerCase() == "button") {
console.log("you have clicked the button!");
this.state.clicked = true;
this.reRender();
}
}
render() {
if (this.state.clicked) {
return this.html`<div>
<h1>Here should be the original content of this element!</h1>
<p>(but actually, it's been overwritten, never to return)</p>
<div style="border: 1px solid black; padding: 1em;">
${this.children}
</div>
</div>`;
} else {
return this.html`<button>Click to show content!</button>`;
}
}
}
Tonic.add(ClickToShow);
</script>
</body>
</html>
I would have expected this.children to always be the two paragraph elements. However, those are lost entirely when the component renders its button. What's the best way to keep the original content around so that it can be used?
What you're looking for is this.elements (here is an example). We picked another property name so we could leave this.children alone. I think React uses this.children though, maybe this is confusing and we should just override this.children.
Aha, yes, yes it is! That works great; thank you! I don't think the docs mention this.elements at all, so that might be a nice update to add to the section about this.children for future people?
ok agreed, the docs could definitely use a mention about this :)