Live Chat Icon For mobile
Live Chat Icon

How do I create components in Blazor dynamically?

Platform: Blazor| Category: Components

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

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.