👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Blazor WASM Dynamic Component

Blazor WASM Dynamic Component

Author - Abdul Rahman (Bhai)

Blazor

34 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

What we gonna do?

In this article, let's learn about <DynamicComponent> in Blazor.

Note: If you have not done so already, I recommend you read the article on Blazor WASM Virtualization.

Why we gonna do?

As its name implies, <DynamicComponent> is a component that allows us to dynamically render components. The idea is that we pass the type of the component to render, and, optionally, its parameters, and voila, the component is rendered.

You don't need to iterate through components and use complex conditionals, use reflection, declare a bunch of RenderFragments, or even build your own render tree. It can get complicated when dealing with parameters and complex data graphs, and none of these solutions are any good, really.

How we gonna do?

How to use Dynamic Component in blazor?

To start using <DynamicComponent>, consider the following example

In the above example,

  • componentType specifies the type.
  • parameters specifies component parameters to pass to the componentType component.

<DynamicComponent Type="@componentType" Parameters="@parameters" />

@code {
    private Type componentType = ...;
    private IDictionary<string, object> parameters = ...;
}
        

When to use Dynamic Component in blazor?

<DynamicComponent> is can be in following scenarios,

  • Dynamically Rendering Widget components in dashboard based on User Preference or UI Settings.
  • Dynamically generating forms from a JSON data stored in database.
  • Dynamically Rendering components based on user choice for different line of business. Example collecting data from user for type of insurance selected. Each insurance component can have different validations and business logics.

Let's try rendering simple input components based on user selection. Let's create 3 components.

A simple <input type="text" />


<label>
    @Label
    <input type="text" />
</label>

@code {
    [Parameter] public string Label { get; set; }
}
        

A simple <input type="checkbox" />


<label>
    <input type="checkbox" />
    @Label
</label>

@code {
    [Parameter] public string Label { get; set; }
}
        

A simple <input type="radio" />


<label>
    <input type="radio" />
    @Label
</label>

@code {
    [Parameter] public string Label { get; set; }
}
        

Steps

  1. Let's start by adding all the three components as option in <select> drop down and hook an @onchange="RenderComponent".
  2. When the user select's a choice from dropdown, we can get the component type in the @onchange event using event args as type = Type.GetType($"BlazorDemoComponents.{eventArgs.Value}");.
  3. Now <DynamicComponent> will render the selected component and pass the parameters using Parameters="@components[type.Name].Parameters". Here we are passing Label parameter to each input component using IDictionary<string, object> parameter.
  4. Note that Type is required parameter and Parameters is optional parameter in <DynamicComponent>.

<select @onchange="RenderComponent">
    <option>Select</option>
    <option value="@(nameof(TextboxComponent))">Text Box</option>
    <option value="@(nameof(CheckboxComponent))">Check Box</option>
    <option value="@(nameof(RadiobuttonComponent))">Radio Button</option>
</select>

@if(type is not null)
{
    <DynamicComponent Type="@type" Parameters="@components[type.Name].Parameters"></DynamicComponent>
} 

@code {
    Type? type;
    private Dictionary<string, ComponentMetadata> components = new()
    {
        {
            nameof(TextboxComponent),
            new ComponentMetadata
            {
                Name = "Text Box",
                Parameters = new() { { "Label", "Text Box" } }
            }
        },
        {
            nameof(CheckboxComponent),
            new ComponentMetadata
            {
                Name = "Check Box",
                Parameters = new() { { "Label", "Check Box" } }
            }
        },
        {
            nameof(RadiobuttonComponent),
            new ComponentMetadata
            {
                Name = "Radio Button",
                Parameters = new() { { "Label", "Radio Button" } }
            }
        }
    };

    public void RenderComponent(ChangeEventArgs eventArgs)
    {
        type = Type.GetType($"BlazorDemoComponents.{eventArgs.Value}");
    }

    public class ComponentMetadata
    {
        public string? Name { get; set; }
        public Dictionary<string, object> Parameters { get; set; } = 
            new Dictionary<string, object>();
    }
}
        
Demo Space

Summary

In this post, we walked through the new <DynamicComponent>, which allows you to render components when you don't know your types at runtime. We were able to render a component based on what a user selects from a drop-down list. We also explored how to pass in parameters to the <DynamicComponent> as well.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • Blazor
  • Dynamic
  • Component
  • Dynamically-rendered