Blazor - How to create Components dynamically

When developing web apps with C#, the Blazor framework is one of the most powerful options. In addition to supporting component-based architecture, Blazor offers support for Virtual DOM, much like other client-side frameworks such as Angular and React. Components are usually produced using razor files, but they can also be crafted with C# code if desired.

In this blog post, I will show you how to create a Blazor component programmatically. Here I will develop a Blazor component, DateTimeComponentThat renders the current date-time on the page.

Let’s consider the following code snippet. I have created a class DateTimeComponent and derive from ComponentBase class.

public class DateTimeComponent : ComponentBase
    {
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {

            builder.OpenElement(0, "h1");
            builder.AddContent(0, DateTime.Now);
            builder.CloseElement();

        }
    }
}

To create a component, we must override the method BuildRenderTree. RenderTreeBuilder has a lot of helper methods to create Virtual DOM. In the above method, I add the H1 tad, and inside that, I add DateTime content.

OpenElement(Int32, String)

OpenElement

Appends a frame representing an element, i.e., a container for other frames. In order for the RenderTreeBuilder state to be valid, you must also call CloseElement() immediately after appending the new element’s child frames.

CloseEelement

Marks a previously appended element frame as closed. Calls to this method must be balanced with calls to OpenElement(Int32, String).

Index.razor

AddContent

Appends a frame representing markup content.

<DateTimeComponent></DateTimeComponent>

@code {

}

Live Demo

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru