6

Is there any way to create and add lightning web components dynamically in the component tree ? I mean the equivalent one in Aura is $A.createComponent().

The usual Web Components can be dynamically created through standard DOM APIs like document.createElement('c-my-cmp') or element.appendChild(element), but as far as I tried in pre-release org it would not work at all.

7

This question has been posted multiple times in the pilot group . The short answer is there is no equivalent for the $A.createComponent() API currently in the LWC .

Currently the team recommends below options

1) Create if branches on the template only load them when a certain condition is meet (yes this is no ideal and not what you are looking for).

2) You can have multiple html templates in your component. You can have a render() method that can switch which template to use based on some conditions.

Looks like option 2 seems more viable approach .

Below is the example shown for this use case

import { LightningElement } from "lwc";

import loadingTemplate from "./loading.html";
import finalTemplate from "./fancyTemplate.html";

export default class HelloWorld extends LightningElement {
@track isLoading = false;

  render() {
     return this.isLoading ? loadingTemplate : finalTemplate;
   }
}

Providing true dynamic creation seems to be technically challenge as per the conversation in the pilot chatter group .

  • The TLDR here is that this is much, much, much more performant. – joshbirk Dec 17 '18 at 16:54
  • 2
    Neither of the above is helping. I'm currently seeking a possibility to bring a React app to LWC, which is dynamically rendering DOMs via react-dom. When I heard about LWC first, I thought it would become possible as it is based on the standard (custom elements). Additionally I also heard someone is saying "LWC components are 'first-class' DOM elements". If we cannot create components through the DOM API, we should stop the applause. – stomita Dec 18 '18 at 4:02
  • I think you should present what you need to LWC team and see what's in roadmap .I am sure since it's start there will be plans to provide something along those lines . – Mohith Shrivastava Dec 18 '18 at 4:05
2

Edit: After testing this in a preview scratch org, I get the error:

LWC1518: Invalid LWC imported identifier "createElement"

It looks like they have very intentionally prevented dynamic component creation which is quite disappointing and makes LWC in it's current state significantly less flexible than aura components. I'll leave the rest of my post in the hopes that createElement returns one day.


I'm quite interested in this ability as well as it's something I've seen used heavily within lightning components (now aura components).

I played around with it in the playground and there does seem to be decent support for this.

The playground gives you main.js which contains the following code by default:

// This is the main entry point to the playground. By default,
// it simply creates a single lightning web component, and adds
// it to the DOM tree.

import * as Engine from 'lwc';
import App from 'c-app';

const element = Engine.createElement('c-app', { is: App });
document.body.appendChild(element);

Based off this (the last two lines) I was able to:

  1. Create a component, c-example which exports the class Example that does nothing except render a div with some text using an @api field called name
  2. Create a component, c-renderer which has two @api fields, component-name which is the string name of the class (c-example) and component-class which is a reference to the class (Example)
  3. Render an element of the class dynamically using the code from main.js
  4. Alter the Example's name field directly through JavaScript

The point of this was not to create something useful (this is a component that really does nothing when you think about it) but to test the ease with which you can not only render components but render them without knowledge of what component you're rendering. I think this is a key feature for building heavily dynamic components. It also tests the ability to pass data to these components after rendering them which is also key.

The full playground is available here.

The gist of the code is:

example.js

import { LightningElement, api } from 'lwc';

export default class Example extends LightningElement {
    @api
    name = 'default';
}

example.html

<template>
    <div>
        This is dynamically rendered content. Its name is {name}
    </div>
</template>

renderer.js

import { LightningElement, api, createElement } from 'lwc';

export default class Renderer extends LightningElement {
    _componentName;

    @api get componentName() {
        this._componentName;
    }

    set componentName(value) {
        this._componentName = value;
        this.renderContent();
    }

    _componentClass;

    @api get componentClass() {
        this._componentClass;
    }

    set componentClass(value) {
        this._componentClass = value;
        this.renderContent();
    }

    renderContent() {
        if (!this._componentClass || !this._componentName) return;

        const element = createElement(
            this._componentName, 
            { is: this._componentClass }
        );

        element.name = 'not default';

        document.body.appendChild(element);
    }
}

renderer.html

<template>
    <div>
        This is statically rendered content
    </div>
</template>

app.js

import { LightningElement, track } from 'lwc';
import Example from 'c-example';

export default class App extends LightningElement {
    // I could not reference Example directly. It had to be in a variable.
    componentClass = Example;
}

app.html

<template>
     <c-renderer component-name="c-example" component-class={componentClass}></c-renderer>
</template>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.