How do I create components in Blazor dynamically?
Nov 21, 2020
Blazor,
ASP .NET Core Blazor,
Blazor FAQ,
How to create components in Blazor dynamically,
5984 Views
This code will help you to understand how to create components in Blazor dynamically.
Blazor applications are based on components. A component in Blazor is an element of UI, such as a page, input, and dialogs. The component class is usually written in the form of a Razor markup page with a .razor file extension. Components in Blazor are formally referred to as Razor components.
You can render the component at runtime using RenderFragment. The RenderFragment class allows you create the required content or component in a dynamic manner at runtime. In the following code example, the Input text Component is created at runtime on button click.
<div id="component-container">
@DynamicRender
</div>
<button @onclick="RenderComponent">Dynamic Component</button>
@code {
private RenderFragment DynamicRender { get; set; }
private RenderFragment CreateComponent() => builder =>
{
builder.OpenComponent(0, typeof(TextBox));
builder.AddAttribute(1, "Title", "Enter your text");
builder.CloseComponent();
};
}
[TextBox.razor]
<input placeholder="@Title" />
@code {
[Parameter]
public string Title { get; set; }
}


