Creating Blazor fragments

At some point you may need to dynamically create elements of mark-up in a Blazor application. For example, you might create a reusable class library for returning components, icons or the likes depending upon the user.

Ofcourse we can do this from the @code block within a page or we might prefer to simply return mark-up from a function.

Let’s look at a simple example method which, depending upon the id sent to it returns a different icon, here’s an abridge snippet of the code

public static RenderFragment GetIconForId(int id)
{
   var iconType = typeof(ListIcon);
   switch (id)
   {
      case 0:
         iconType = typeof(HomeIcon);
         break;
      case 1:
         iconType = typeof(NotificationImportantIcon);
         break;
      // etc.
   }
   
   return builder =>
   {
      builder.OpenComponent(0, iconType);
      builder.CloseComponent();
   };
}

As you can see we return a RenderFragment which is actually just a delegate which takes a RenderTreeBuilder argument. From this builder we create/append a child component, the first value is a sequence (a position of the instructions in the source code) followed by the type of the child component to add.

If the case above, the HomeIcon is an Icon from Skclusive.Material, which is ultimately an Microsoft.AspNetCore.Components.IComponent.

So anything that takes a RenderFragment will now display the icon that’s returned via the method in our example.

We can also use AddAttribute to our component, see RenderTreeBuilder for more information.

Basically it’s not dissimilar (as you’ve expect) to create XML documents using the XmlDocument classes etc.