How can I dynamically create HTML components in Marko?

265 Views Asked by At

I want to create new Marko components every time the user clicks a button — by calling something like the JavaScript DOM method document.createElement("tag"). How can I do this in Marko, not just with ordinary HTML tags, but with custom Marko tags?

What I tried: document.createElement("custom-marko-component")

Expected behavior: Marko engine compiles a new instance of the custom component.

Actual behavior: The browser makes a useless new <custom-marko-component></custom-marko-component>.

1

There are 1 best solutions below

0
On

Use Marko's rendering functions (documentation: https://markojs.com/docs/rendering/):

Example:

// Create the custom component, like document.createElement() but asynchronous.
// Import `./custom-marko-component.marko`
var customComponent = require("./custom-marko-component"); 
var resultPromise = customComponent.render({});

// Insert the custom component into the webpage.
resultPromise.then(result => {
  result.appendTo(document.body);
});