How to render a dynamic Component with Blazor
How to render a dynamic Component with Blazor

How to render a dynamic Component with Blazor

2020, Oct 21    

Hi All! Today we’re going to see a simple technique to render a dynamic Component with Blazor.

Suppose you want to create a generic Component to handle lists. Something very easy like this:

@typeparam TItem

<ul>
@foreach(var item in Items){
    <li>....</li>
}
</ul>

@code{
    [Parameter]
    public IEnumerable<TItem> Items {get;set;}
}

The first thing to notice is that we used the @typeparam directive to specify the Generic type.

But if you look carefully, you can see that we haven’t defined a way to render the items. We want this ListComponent to be as generic as possible, so we need a way to provide the layout definition and logic somewhere else.

The easiest way to achieve this is to make use of the RenderFragment delegate. With it, we can define the rendering logic in our parent Component and pass it over to the List Component.

The parent Component will look like this:

<ListComponent Items="_items" Renderer="_customRenderer" />

@code {
	private RenderFragment<Foo> _customRenderer = (model) => @<span>@Foo.Bar</span>;
	private IEnumerable<Foo> _items = ...;
}

And this will be our new ListComponent:

@typeparam TItem

<ul>
@foreach(var item in Items){
    <li>@Renderer(item)</li>
}
</ul>

@code{
    [Parameter]
    public IEnumerable<TItem> Items {get;set;}
    [Parameter]
    public RenderFragment<TItem> Renderer {get;set;}
}

In the example we used the generic version of RenderFragment, super handy in contexts like this.

If you like Blazor and game programming, don’t miss my series on 2D Gamedev!

Did you like this post? Then