How to insert an Element into the dom in backdraft

30 Views Asked by At

How do you insert an Element into the DOM via a bdAttach?

class Foo extends Component {
    bdElements() {
        return e.div(
            e.div(
                { bdAttach: 'contentGoesHere' }
            ),
        );
    }

    insertContent() {
        const content = e.span('content');
        // WHAT GOES HERE, TO INSERT THE CONTENT INTO this.contentGoesHere ?
    }
}
1

There are 1 best solutions below

1
On

You have two choices depending upon whether content is (A) just a plain old DOM tree (perhaps only one node as depicted in your question), or (B) a Component that you intend to manage.

Case A

Either of these examples for Case A are fine and real and largish programs will have a few of these...though this pattern is not common.

insertContent() {
    // insert(), and create() are functions in the bd-core library
    insert(create('span', {innertText:'content'}), this.contentGoesHere);

    // --or--, using createHtml(), also a function in the bd-code library
    insert(createHtml('<span>content</span>'), , this.contentGoesHere);
}

Case B

One of the examples below is an antipattern.

insertContent() {
    // normal and common pattern: 
    // insert a child Component that is managed by Foo
    this.insChild(e.span('content'), this.contentGoesHere);

    // This is an anti-pattern:
    // render will create a Component instance on-the-fly; however(!)...
    // when Foo is unrendered it will destroy its DOM tree, which 
    // will destroy the DOM tree of the dynamically-created content which
    // is actually being managed by the component-created-on-the-fly. It will
    // still usually all work (depending upon what you expect of 
    // `this._createdContent`) (and, perhaps you don't even take a
    // reference to the created content).

    this._createdContent = render(e.span('content'), this.contentGoesHere);
}