Creating and using components

Creating and using components

Introduction

Blazor components act as the building blocks of the application, encapsulating the logic needed to craft the user interface. Essentially, any segment of our application can be structured as a component, be it a home page, registration form, login form, or error page. Leveraging components helps in segmenting the application into smaller, more manageable, and reusable pieces. They stand as the foundational elements in every Blazor application.

 

Structure of a Blazor Component
A Blazor component is primarily composed of two parts:

 

Razor Markup (.razor): This is where you define the UI of the component. It combines HTML with Razor syntax, which lets you inject dynamic content based on the component’s data and logic.

 

C# Code Block: Embedded within the Razor file, or separated into a code-behind file, this block contains the component’s logic, data, and event handlers.

It is very important to note that all visible items displayed in a Blazor application are components.

For example, a page called “Events” that contains a table can be seen as a component containing another component.

 

In general, pages contain a set of reusable components.

In the following example, we are going to create a component to display a list of events.

The code below displays the table above:

				
					@page "/events"
@using MataHub.Data;
@using MataHub.Models;
<h3>EventList</h3>
@if (events == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Date</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var evt in events)
            {
                <tr>
                    <td>@evt.Name</td>
                    <td>@evt.Date.ToShortDateString()</td>
                    <td>@evt.Location</td>
                </tr>
            }
        </tbody>
    </table>
}
@code {
    private List<Event> events;
    protected override async Task OnInitializedAsync()
    {
        // Simulating async call for fetching data
        await Task.Delay(1000);
        events = EventData.GetEvents();
    }
}

				
			

Here’s a breakdown of each part:

				
					@page "/events"
@using MataHub.Data;
@using MataHub.Models;
<h3>EventList</h3>
				
			

1.`@page “/events”` – Declares a new route that the Blazor application will recognize. In this case, visiting `/events` in the web browser will display this component.
2. `@using MataHub.Data;` and `@using MataHub.Models;` – These are namespace imports. The code is expecting classes from these namespaces to be used later in the code.

 

HTML Markup

				
					<h3>EventList</h3>
@if (events == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <!-- table code -->
}

				
			

– The `h3` tag simply displays the title “EventList”.
– The `@if` condition checks if `events` is `null`. If it is, “Loading…” will be displayed, otherwise, a table will be displayed.

 

The Table

				
					  <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Date</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var evt in events)
            {
                <tr>
                    <td>@evt.Name</td>
                    <td>@evt.Date.ToShortDateString()</td>
                    <td>@evt.Location</td>
                </tr>
            }
        </tbody>
    </table>
				
			

The table uses Bootstrap classes (presumably, judging by `class=”table”`) and consists of a header (`thead`) and a body (`tbody`). The body iterates over each `Event` object in the `events` list to populate the table rows.

 

The Code Block

				
					  <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Date</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var evt in events)
            {
                <tr>
                    <td>@evt.Name</td>
                    <td>@evt.Date.ToShortDateString()</td>
                    <td>@evt.Location</td>
                </tr>
            }
        </tbody>
    </table>
				
			

1.`private List events;` – A private field that holds the events to be displayed.

2. `protected override async Task OnInitializedAsync()` – This is a lifecycle method in Blazor that gets called when the component is initialized. Inside this method, the events data is being fetched.

– `events = EventData.GetEvents();` – Data is fetched using a static method `GetEvents()` from the `EventData` class. Replace this with data fetching logic relevant to your application.

 

Conclusion

This is a straightforward example, but it encapsulates many of the core features of Blazor. It demonstrates route declaration, conditional rendering, table rendering using loops, and asynchronous data fetching in the lifecycle method.

 

However, while this code snippet introduces us to the concept of components in Blazor, it’s worth noting that the component is not reusable as it is. Its functionality and presentation are tightly coupled, and the logic for fetching event data is hardcoded within the component itself. Reusability is one of the key advantages of component-based architectures like Blazor, so in our next blog post, we’ll delve into the art of creating reusable components. We will explore how to design components that can be easily reused across different parts of an application, making our codebase more maintainable and extensible.

 

Stay tuned for more!

Share:

Scroll to Top