What's the recommended way of rendering a Blazor component dynamically?
You have to create a RenderFragment, and use that as a renderer of your polymorphic component... I've used the default Blazor's template Counter component as a parent (CounterParent), and then the CounterChild inherits the CounterParent. I hope it helps!! Regards!
@page "/"
@foreach (CounterParent counter in components)
{
RenderFragment renderFragment = (builder) => { builder.OpenComponent(0, counter.GetType()); builder.CloseComponent(); };
<div>
<div>Before the component</div>
@renderFragment
<div>Afterthe component</div>
</div>
}
@code
{
List<CounterParent> components = new List<CounterParent>() { new CounterParent(), new CounterChild() };
}
You could use a switch statement that checks the types. You can place components in each of the cases, or render your li however you like.
<ul>
@foreach (fruit in fruits)
{
switch(fruit)
{
case PearComponent p:
<PearComponent ParameterOfSomeSort="p"></PearComponent>
<li>Or render pears like this, if you want the li in it</li>
break;
case AppleComponent a:
<AppleComponent></AppleComponent>
break;
case BananaComponent b:
<BananaComponent></BananaComponent>
break;
case RaspberryComponent r:
<RaspberryComponent></RaspberryComponent>
break;
}
}
</ul>