5

I was researching for an alternative for document.createElement() in LWC when I stumbled upon this article from SF's GitHub page: https://github.com/salesforce/lwc/blob/master/docs/architecture/web-components.md

In LWC, neither of those are available yet, instead, you have to use a temporary proprietary API:

LWC.createElement('bad-1'); // returns an element

What is LWC in this case, where do I get access to it from? Is it something I need to import like track/wire/api? Or perhaps is it a like the pubsub library?

2 Answers 2

6

This only applies to the LWC OSS (Open Source Software) version. In Salesforce, you won't be able to use this method. There is discussion internally about how/if you'd be able to create components dynamically in Salesforce LWC, but for now, the correct method is to create components from Aura, e.g.:

$A.createComponents(
  ['c:my-lwc-component',{}], 
  function(cmp,err) { 
    if(cmp) { 
      component.set('v.dynamicComponents',cmp);
    } else { 
      alert(err); 
    }
  }
);

You cannot (currently) dynamically create LWC components from LWC components.

2
  • Would this be any different if I need to createElement inside a <div lwc:dom="manual"></div>? Right now I can create an element using innerHTML(inside a dummy div) then once that gets turned into a node I can query for it and use appendChild to move it to another div where it's supposed to go. But this seems like an overkill. I also would like to avoid adding aura.
    – Arthlete
    May 22, 2020 at 17:08
  • 3
    @Arthlete You can create normal HTML elements, just not custom elements. They won't work correctly, won't be the correct data type, etc.
    – sfdcfox
    May 22, 2020 at 17:28
-1

Update on 2021, you can import it from lwc

import { createElement } from "lwc";

It works at least for jest unit tests, I haven't tried using it in a component that gets deployed but I imagine it'd work

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .