Semkado
Semkado

Reputation: 25

Blazor dynamically createElement and appendChild

i want to dynamically create DIV Containers via JSInterop in Blazor Webassembly. My approach was to create a CreateElement method in C# which calls createElement in javascript and returns a ElementReference as a Result. But when i run the Following code, i just get an empty object.

C# code:

public object CreateElement(ElementReference elementReference)
{
    return JsRuntime.Invoke<object>("createElement",
        elementReference,
        DotNetObjectReference.Create(this));
}

Javascript code:

createElement(element, objectReference) {
            const newDiv = document.createElement("div");
            return element.appendChild(newDiv);
        }

Upvotes: 1

Views: 7105

Answers (2)

Joey McKenzie
Joey McKenzie

Reputation: 1

As @Porkopek mentioned, there's not really a good reason to do this as it more or less defeats the purpose of using Blazor to dynamically render markup.

If you absolutely have to use createElement, you should bind your JS interop code to the window object to invoke:

window.createDivElement = createElement(element, objectReference) {
  const newDiv = document.createElement("div");
  return element.appendChild(newDiv);
}

Side note, DotNetObjectReference.Create(this) is for calling back into C# component methods via the [JSInvokable] attribute and probably not needed here.

Upvotes: 0

Porkopek
Porkopek

Reputation: 1022

You don't need JS for that. Blazor was made so you don't have to manipulate the DOM. Create components. Manipulating the DOM this way defeats the purpose for which Blazor was made. You may want to start with some basics at https://learn.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-3.1

Upvotes: -1

Related Questions