Hey There! ๐๐ป
I was working on a component for my chat application the other day, and I needed a way to add Select elements, I know there are different ways of doing that, but I decided to try something new with it, and found the result to be pretty nice, so I thought I'd share it with you as it could be useful for you as I'm sure you'll come across the need of having a way to allow users to select items, elements, users or whatever it is.
Before you read any further, I'd like to show you where I needed such a functionality.
Creating group chats! ๐ฌ
I built and released a simple web based chat application a while ago, and I wanted to continue developing it, so one feature that sounded fun to have, is group chats.
I'm sure you've attempted to at least once create a group in some messaging app, like WhatsApp, Telegram, Messenger or any of them. One very necessary step is selecting the contacts you want to have in your group chat right?
So without further talking, here's the final result I had with my chat application:
I will not use the chat application's code to show you how to implement that, instead, we'll code something from scratch, but in case you're interested, you can checkout the source code for the whole app here:
https://github.com/rasheed-k-mozaffar/Flow
If you want to look at the source code for the component directly you can use this link:
https://github.com/rasheed-k-mozaffar/SelectComponentDemo
What will we build? ๐ ๏ธ
We'll create a list of fruits, and display them on the page, we'll write the select logic for them and make it that when at item is selected, it's background gets highlighted.
The idea is simple, but actually the logic works almost the exact same way regardless of the task you want to achieve, and if you want to add more UI customization or maybe animations to it, it won't be difficult to do so.
Let's Get Started ๐
I created a basic Blazor WebAssembly project for this article, and I added this starter code inside Index.razor
:
@page "/"
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
<ul>
@foreach (var fruit in fruits)
{
<li style="font-size: 20px; cursor: pointer"
class="p-1 mb-1">
@fruit
</li>
}
</ul>
@code {
private List<string> fruits = new List<string>()
{
"Strawberries \ud83c\udf53",
"Apples \ud83c\udf4f",
"Bananas \ud83c\udf4c",
"Melons \ud83c\udf48",
"Oranges \ud83c\udf4a",
"Pears \ud83c\udf50",
"Cherries \ud83c\udf52",
"Avocados \ud83e\udd51"
};
}
โ ๏ธ NOTE: The set of characters after the name of each fruit are Unicode escape sequences that represent the respective emoji for each fruit, don't worry abut them, they're nothing important.
The Data Structure of Choice For the Select ๐๏ธ
We need a place to keep track of the items we selected right?
One thing to keep in mind when it comes to selects is, mostly always the selectable elements are meant to be unique, be it the fruits, the contacts from the create group chat feature, and many others are alike.
So, we know the selected items are going to be distinct. What does that suggest?
If you thought of a HashSet<T>
, then you're AWESOME.
This data structure has incredible performance for lookups and is great for storing unique items, which is exactly what we need here.
Add this code below the list initializer:
private HashSet<string> selectedFruits = new HashSet<string>();
private void OnFruitClicked(string fruit)
{
// implementation is up next!
}
The code creates a hash set of strings, and defines a method called OnFruitClicked
, this method is what will perform the select and unselect of a given item. You'll be shocked by how simple the implementation for this method actually is.
As a matter of fact, the implementation is exactly 2 lines of code. Before we write them, we'll discuss the logic the implementation will use.
The Select Logic โ๏ธ
When the user clicks a fruit, we want to pass its name to the method, the OnFruitClicked
method will take the name, and attempt to add it to the selectedFruits
set. If you've used a hash set before, you'll know that one of its inherent characteristics is that duplicates aren't allowed.
In C#, the HashSet's Add
method, will take an item, and attempt to add it, if the item is already present, the call will return false
, and if it got added, it'll return true
.
In the UI, we will update items as they are selected and unselected. We'll do so by giving a selected item a green background, this will be done through a lookup using the hash set too.
Putting the Pieces Together ๐งฉ
Let's wrap everything up by implementing the method that'll be called when a fruit is clicked. Start by adding this code to the OnFruitClicked
method:
private void OnFruitClicked(string fruit)
{
if (!selectedFruits.Add(fruit))
{
selectedFruits.Remove(fruit);
}
}
That's pretty much it for this function.
It checks if adding a new fruit yields back false, it means the fruit is already there, thus it'll unselect it (It does so by removing it from the set). In case the fruit was indeed unselected, it'll simply add it to the selected fruits hash set. How simple?
Moving on, we need to hook up this method to each <li>
element that displays a fruit, we'll do so by doing the following:
<ul>
@foreach (var fruit in fruits)
{
<li @onclick="(() => OnFruitClicked(fruit))"
style="font-size: 20px; cursor: pointer"
class="p-1 mb-1 @(selectedFruits.Contains(fruit) ? "bg-success" : null)">
@fruit
</li>
}
</ul>
The changes we made hook an anonymous function to the onclick
event, which in turn calls OnFruitClicked
passing to it the name of the fruit item that was clicked. The second interesting change is actually inside the class
attribute.
The added C# expression uses the ternary operator
condition ? value-for-true : value-for-false
If selectedFruits
contains the fruit item, we append the class bg-green
to the list element, which will highlight and differentiate selected items from non-selected items.
That's pretty much everything you need for adding selects, checking if the set contains the item is what you would use to style elements or maybe add some fancy animations if you want.
Let's Test It ๐งช
Run the app and try clicking around the fruits, you'll see how the select and unselect are in fact working.
As you can see, it works as intended, now it doesn't do much, but you now have a fully functional mechanism for selecting & unselecting items, you can figure out more use cases for this and even take it to a whole new level regarding the UI by adding some creative touch to make it more interesting than the lame green background of Bootstrap.
Summary
We looked in this article at how we can create a select & unselect mechanism in Blazor using as little code as possible, while also keeping it efficient and clean.
โ ๏ธ NOTE: The code I've shown to you in this article is exactly the same as the code I've used in my chat application, I came up with this mechanism while building the group chats feature and decided to make an article of it as hopefully someone might find it useful in some scenario.
I hope you found that useful, and that you learned something new. If you got any better ways than the one I discussed in this article, please share it in the comments, it'd really help us all learn!
Thanks for reading! ๐๐ป
Top comments (0)