Removing elements after an animation in Blazor

 
 
  • Gérald Barré

Smoothly removing elements from the UI improves user experience. One approach is to use a CSS animation to fade out an element before removing it from the DOM. To do this, add a CSS class to trigger the animation, then listen for the transitionend or animationend event to remove the element from the list.

First, register the transitionend and animationend event handlers so they can be used in components. This requires ASP.NET Core 6 or later.

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, 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?