Creating a reusable loading indicator in Blazor

 
 
  • Gérald Barré

Blazor allows writing components to encapsulate common behaviors. For instance, you may often need to show a loading indicator while loading data from a database or a remote service, or while processing a form. You can also use a loading component to indicate any long operation.

This Loading component is very basic and simple to create, but so useful!

Razor
@if (IsLoading)
{
    if (LoadingTemplate != null)
    {
        @LoadingTemplate
    }
    else
    {
        <div class="spinner-border"></div>
        <span style="display: inline-block; vertical-align: super">@LoadingText</span>
    }
}
else
{
    @ChildContent
}

@code{
    [Parameter]
    public bool IsLoading { get; set; }

    [Parameter]
    public string LoadingText { get; set; } = "Loading...";

    [Parameter]
    public RenderFragment LoadingTemplate { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

You can use the component to display a loading indicator while loading data:

Razor
@page "/"

<Loading IsLoading="customers is null">
    <ul>
        @foreach (var customer in customers)
        {
            <li>@customer.Name</li>
        }
    </ul>
</Loading>

@code {
    private List<Customer> customers;

    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(1000); // simulate loading
        customers = new List<Customer>();
    }
}

Or you can use it to show that an action is in progress:

Razor
@page "/"

<button type=button @onclick="ProcessAsync">Process</button>

<Loading IsLoading="isProcessing">
    Please wait, while we work our Magic 🦄
</Loading>

@code {
    bool isProcessing;

    Task ProcessAsync()
    {
        isProcessing = true;
        try
        {
            await Task.Delay(1000); // simulate loading
        }
        finally
        {
            isProcessing = false;
        }
    }
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub