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);


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)


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.


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



Appends a frame representing markup content.


@code {


Live Demo

Next Post Previous Post
No Comment
Add Comment
comment url