Search code examples
cssrazorblazor

How to highlight selected list item in blazor?


I have created a simple list in a razor component.it is a simple HTML list with foreach loop.

<ul>
           @foreach (var itm in matchingLocations)
           {
            <li>
                <div class="d-flex">

                    <div class="py-2 pr-2">
                        <i class="fas fa-map-marker-alt text-glow-1"></i>
                    </div>
                    <div class="py-2"><span class="sub-title-2">@itm.CodeName</span></div>
                   
                </div>

            </li>

            
            }
       
    </ul>

Now I have needed to add the following 2 features to the list

  1. when click on one list item, it should be highlighted.

  2. if we want to click on another item,while one item is already highlighted, the currently highlighted item should be unhighlighted and clicked item should be highlighted.

. how can I do this using blazor? anybody who knows about this, please help me.


Solution

  • There are many ways to do this. Here's a demo page showing one:

    @page "/"
    @foreach (var item in Countries)
    {
        <div class="@DivCss(item) p-2" @onclick="() => SetSelect(item)">
            @item.Name
        </div>
    }
    
    @code {
    
        List<Country> Countries = new List<Country>
    {
            new Country { Name = "Australia"},
            new Country { Name = "Spain"},
            new Country { Name = "Croatia"}
        };
    
        List<Country> SelectedCountries = new List<Country>();
    
        class Country
        {
            public string Name { get; set; }
        }
    
        bool IsSelected(Country country)
            => SelectedCountries.Any(item => item == country);
    
        string DivCss(Country country)
            => IsSelected(country) ? "bg-success text-white" : "bg-light";
    
        void SetSelect(Country country)
        {
            if (IsSelected(country))
                SelectedCountries.Remove(country);
            else
                SelectedCountries.Add(country);
        }
    }