In this lesson, you will learn how to use the DynamicComponent container to render UI elements on-the-fly based on application state or external configuration.
The Problem: Rigid UI
Usually, you hardcode components into your Razor files. But what happens if you are building a dashboard where the layout depends on a user's role, or a settings panel that changes based on a database configuration? Instead of writing a giant switch statement with dozens of <Component /> tags, you can use the DynamicComponent to inject a specific component type at runtime.
How it Works
The DynamicComponent takes a Type object and a Dictionary<string, object> of parameters. The framework handles the instantiation and lifecycle for you.
Imagine you have a configuration object that tells your app which "Widget" to show:
@* Dashboard.razor *@
@if (selectedWidgetType != null)
{
<DynamicComponent Type="@selectedWidgetType" Parameters="@widgetParams" />
}
@code {
private Type? selectedWidgetType;
private IDictionary<string, object>? widgetParams;
protected override void OnInitialized()
{
// Data-driven selection: This could come from an API or DB
selectedWidgetType = typeof(WeatherWidget);
widgetParams = new Dictionary<string, object>
{
{ "City", "London" }
};
}
}
Why Use This?
- Decoupling: Your main container doesn't need to know the implementation details of every possible component.
- Configuration Driven: You can change the layout of your application by updating a simple JSON config file or database record, allowing your UI to evolve without recompiling the entire project.
- Efficiency: It eliminates "component bloat" in your markup, keeping your files clean and readable even as your application grows in complexity.
When using DynamicComponent, remember that the Type passed must be a class that implements IComponent. Because parameters are passed as a dictionary, you lose some compile-time type checking, so ensure your keys match the [Parameter] properties of your target components exactly.
Key Takeaway: The DynamicComponent allows you to treat UI pieces as data, enabling you to switch or inject components dynamically at runtime based on your application's logic or data-driven configurations.