Skip to content

this.children gets overwritten by Tonic changes #86

@stuartlangridge

Description

@stuartlangridge

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions