Blazor: How to create reusable render fragment?

Viewed 3105

I have a following markup that I use often:

<SfDropDownList DataSource="@Model.Customers" TItem="Customer" TValue="Customer">
    <DropDownListTemplates TItem="Customer">
        <ItemTemplate Context="customer">
            <span>@customer.Name</span><span class="float-right">@customer.Site</span>
        </ItemTemplate>
    </DropDownListTemplates>
</SfDropDownList>

How do I reuse DropDownListTemplates with the same parameters in multiple components?

I was thinking, that I create I create a custom class inherited from DropDownListTemplates:

@inherits DropDownListTemplates<Customer>
@code { 
    override void OnAfterRender(bool firstRender)
    {
        // this.ItemTemplate = ??
        base.OnAfterRender(firstRender);
    }
}

but how do I set ItemTemplate which is a RenderFragment parameter in the base class?

I want to avoid wrapping SfDropDownList to a custom component

1 Answers

You can set the default value for a RenderFragment parameter as below.

@ChildContent

@code {
    [Parameter] public RenderFragment ChildContent {get; set;} = @<p>Some text here</p>;
}

Source: blazor-university.com


Edit to add: You can also define a reusable RenderFragment in code.

public static RenderFragment SayHello = __builder =>
{
    <h1>Hello!</h1>
};

A RenderFragment delegate can also take parameters.

<div class="chat">
    @foreach (var message in messages)
    {
        @DisplayChatMessage(message)
    }
</div>

@code {
    RenderFragment<ChatMessage> DisplayChatMessage = message => __builder =>
    {
        <div class="chat-message">
            <span class="author">@message.Author</span>
            <span class="text">@message.Text</span>
        </div>
    };
}

Source: ASP.NET Core Blazor Web Assembly Performance Best Practices

Related