Blazor Expanding Cards


 

This provides a cool look that can be used for displaying products, pictures, or a wide range of items to your users.

For our sample, we will be using images, set the background image.  It makes a nice demo.


HTML

It turns out this is effect fairly easy to implement.  You have a container and a DIV for each card that you want.

    <div class="container">
        <div class="panel">
            <h3>Explore The World</h3>
        </div>
        <div class="panel">
            <h3>Wild Forest</h3>
        </div>
        <div class="panel">
            <h3>Sunny Beach</h3>
        </div>
        <div class="panel">
            <h3>City on Winter</h3>
        </div>
        <div class="panel">
            <h3>Mountains - Clouds</h3>
        </div>
    </div>


CSS 


The CSS is straightforward as well.  The container is a flexbox.  Each panel within the flexbox is positioned absolutely with a flex of 0.5.

The "trick" comes on with the on-click event.  When a user clicks on one of the panels, we add an "active" class to that panel.  The active class sets the item to flex of 5.


Blazor Stuff

Now for the fun stuff, creating the on-click event and handling it.  We will need to know which panel clicked on so we can add the "active" class to the clicked panel.  But we will need to remove the active class from all the other elements.

We have done several times in the past, usually with a class variable for each panel, then within a foreach we would test to see if the item we are on is the one clicked, if so, we would add the active class, else remove the active class.

This process seems ok, but if we add move panels, we have to create more variables and adjust or for loop.  For this solution, I decided to go a different way.


I have 1 variable called "open".  This holds the panel number that has the active class applied.  On a click, we call a method to set "open".  On each panel HTML class section, we use an if to test if this is the clicked panel.  If so, add the active class, else, don't.  

Added to each panel:

        class="panel @(open == 3 ? "active" : "")" @onclick="@(e=>SetActive(3))"

Now if we add more panels, we just increase the index that the panel is, and everything works.

        class="panel @(open == 4 ? "active" : "")" @onclick="@(e=>SetActive(4))"

Summary

That is it.  A very cool effect with a little work.  You should be able to use this in a wide range of applications.




Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor Wizard Step Component