How do you create elements dynamically in Blazor?

Platform: Blazor| Category: Components

We can create elements dynamically in server-side Blazor applications by following this example.

@page "/render-fragment"
 
<button type="button" @onclick="@RenderComponent">
    Trigger rendering
</button>
 
@DynamicFragment
 
 
@code {
    private string dynamicContent = "This is a long text...";
    private RenderFragment DynamicFragment;
 
    private RenderFragment CreateComponent() => builder =>
    {
        dynamicContent = dynamicContent.Replace("long", "long long");
 
        builder.OpenElement(1, "p");
        builder.AddContent(2, dynamicContent);
        builder.CloseElement();
    };
 
    private void RenderComponent()
    {
        DynamicFragment = CreateComponent();
    }
}

Reference link

https://learn-blazor.com/pages/dynamic-content/

Share with

Related FAQs

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

Please submit your question and answer.