Removing elements after an animation in Blazor

 
 
  • Gérald Barré

There are many cases where you want to smoothly remove an element from the UI. A solution is to use an animation to fade out the element before removing it. You can start the animation by adding a class to the element you want to remove. Then, you can use the transitionend or animationend event to actually remove the element.

First, you need to register the transitionend event handler, so you can use it in components. Note that this is possible only starting with ASP.NET Core 6.

C#
using System;
using Microsoft.AspNetCore.Components;

namespace Sample
{
    [EventHandler("ontransitionend", typeof(EventArgs), enableStopPropagation: true, enablePreventDefault: false)]
    [EventHandler("onanimationend", typeof(EventArgs), enableStopPropagation: true, enablePreventDefault: false)]
    public static class EventHandlers
    {
    }
}

Then, you can use it in your components:

Razor
@page "/"
<h1>Sample</h1>

<ul>
    @foreach (var item in items)
    {
        @* ontransitionend will actually remove the item *@
        <li class="@GetClassName(item)" @ontransitionend="e => RemoveItem(item)">
            <span>Item @item</span>

            @* Add the current item to the removingItems collection, so it will add the "removing" class *@
            <button type="button" @onclick="e => RemoveItemWithAnimation(item)">Remove</button>
        </li>
    }
</ul>

@* Define the transition using CSS *@
<style>
    .removing {
        transition: opacity 0.7s linear;
        opacity: 0;
    }
</style>

@code {
    // List of visible items
    List<int> items = Enumerable.Range(0, 50).ToList();

    // List of items being removed
    HashSet<int> removingItems = new();

    void RemoveItemWithAnimation(int item) => removingItems.Add(item);

    void RemoveItem(int item)
    {
        removingItems.Remove(item);
        items.Remove(item);
    }

    string GetClassName(int item) => removingItems.Contains(item) ? "removing" : "";
}

#Additional resources

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