Building a Reusable Accordion Component in Blazor: A Step-by-Step Guide


One of the powerful features of Blazor is the ability to create reusable components, making it easy to build dynamic, interactive web applications while minimizing redundant code. In this post, we’ll walk through how to create a flexible, generic accordion component that can be reused throughout your application, allowing you to pass custom labels and dynamic content for each accordion section.

The Problem: Hardcoded Accordion Sections

Imagine you have an accordion structure with multiple sections that expand and collapse, showing content for different components. If this structure is repeated in several parts of your application, you could end up with a lot of repeated, hard-coded accordion items like this:


<article class="WideArticle Admin mb-2"> <div class="accordion mb-4" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button headerText" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne"> User Authorization </button> </h2> <div id="collapseOne" class="accordion-collapse collapse show"> <div class="accordion-body"> <UserRoleMainPage /> </div> </div> </div> <!-- Other accordion sections... --> </div> </article>

While this works, it has two main downsides:

  1. The accordion labels and content are hardcoded.
  2. It becomes difficult to reuse this structure in other parts of your application.

Let’s fix that by turning this code into a reusable Blazor component that can dynamically accept labels and content!

The Solution: Creating a Generic Accordion Component

We’re going to create a Blazor component that:

  • Accepts an array of labels for the accordion headers.
  • Accepts an array of components or content for the accordion body.

This way, we can use the accordion anywhere in the app with different content, all while maintaining a clean, modular approach.

Step 1: Define the Accordion Component

We’ll start by creating a new Razor component called Accordion.razor. This component will receive two parameters:

  1. string[] Headers: An array of strings representing the titles of each accordion section.
  2. RenderFragment[] Contents: An array of RenderFragment for rendering the dynamic content within each section.

Here’s the code for the Accordion.razor component:


<nav class="accordion arrows"> <header class="box"> <label for="acc-close" class="box-title">System Admin</label> </header> @for (int i = 0; i < Items.Count; i++) { int index = i; var item = Items[i]; var itemId = $"{AccordianId}_collapse_{index}"; <input type="radio" name="accordion" id=@index /> <section class="box"> <label class="box-title" for=@index>@item.Label</label> <label class="box-close" for="acc-close"></label> <div class="box-content"> @item.Content </div> </section> } <input type="radio" name="accordion" id="acc-close" /> </nav> @code { [Parameter] public List<AccordionItem> Items { get; set; } = []; [Parameter] public string AccordianId { get; set; } = "accordionExample"; private void ToggleItem(int index) { Items[index].IsExpanded = !Items[index].IsExpanded; for (int i = 0; i < Items.Count; i++) { if (i != index) { Items[i].IsExpanded = false; } } StateHasChanged(); } }

Key Features:

  • Dynamic Header and Content: The component accepts arrays for the headers (Headers) and body content (Contents), meaning you can pass any string and any child component or content to the accordion.
  • Accordion Toggling: We use the ToggleAccordion method to manage the visibility of the accordion sections, expanding the clicked section and collapsing others.
  • Bootstrap Classes: The collapsed and show Bootstrap classes are conditionally applied to control the accordion's appearance.

Step 2: Using the Accordion Component

Now that we’ve defined the accordion, we can use it by passing different sets of headers and corresponding content. Here’s an example of how to integrate the Accordion component into a page:


@page "/" <AccordionUIControl.Components.UI.Accordion.AccordionControl Items="AccordionItems" />" @code { private List<AccordionItem> AccordionItems = []; private bool allowBudgetGoal = true; // Set your condition here protected override void OnInitialized() { AccordionItems = new List<AccordionItem> { new AccordionItem { Label = "Counter", Content = @<Counter /> }, new AccordionItem { Label = "Weather", Content = @<Weather /> }, new AccordionItem { Label = "Override Viewer", Content = @<OverrideView /> }, new AccordionItem { Label = "Audit Log Viewer", Content = @<AuditTrialView /> } }; if (allowBudgetGoal) { AccordionItems.Add(new AccordionItem { Label = "Set Budget Goal", Content = @<BudgetGoalView /> }); } } }

In this example:

  • We pass an array of strings for the headers, such as “User Authorization” and “Audit Log Viewer”.
  • The Contents array holds different components for each section of the accordion.
  • We conditionally display the BudgetGoalView based on the value of allowBudgetGoal.

Step 3: Adapting to Different Use Cases

This generic accordion component is now versatile. You can reuse it anywhere in your app with different content and labels. Here are a few examples:

  • User Management Dashboard: Use the accordion for user roles, permission settings, and other related components.
  • Settings Panel: Use the accordion to organize sections like user preferences, application settings, and notifications.

The possibilities are endless. By simply passing different strings and components, you can create dynamic, interactive UI sections without duplicating code.


Step 4: Adapting to Different Use Cases

For styling, using isolated CSS will allow the user of the accordion control to style it to theme it to meet their requirements.


Summary

By refactoring your Blazor accordion into a reusable component, you gain flexibility, reduce code duplication, and create a more modular, maintainable application. This accordion component allows you to dynamically pass content and labels, making it adaptable to various scenarios in your Blazor application.

Give this approach a try in your next Blazor project, and you’ll see how reusable components can dramatically improve your development process!


[source code]

Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor - Cool Blur Loading Page