What is Blazor?
Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# and .NET instead of JavaScript. Blazor components are reusable building blocks used to create interactive user interfaces in Blazor applications. In this guide, I'll cover everything you need to know about Blazor components with examples.
A Blazor component is a self-contained, reusable unit of user interface (UI) functionality within a Blazor application. Components in Blazor are similar to components in other frontend frameworks like React or Angular. They encapsulate HTML markup, C# code, and optionally CSS styles, allowing developers to create modular and composable UI elements.
Blazor components follow a component-based architecture, where larger UIs are built by composing smaller, reusable components together. Each component can have its own logic, state, and lifecycle events, making it easier to manage complex UIs and promoting code reusability.
Blazor components can be of two types:
-
Razor Components (or .razor files): These are the most common type of Blazor components, defined using Razor syntax (HTML with C#) in .razor files. They typically consist of a combination of HTML markup and C# code, allowing developers to define the UI and behavior of the component in a single file.
-
Code-Behind Components (or .cshtml and .cs files): These components separate the UI markup (in .cshtml files) from the C# logic (in .cs files). The .cshtml file contains the HTML markup with embedded C# code, while the .cs file contains the C# logic for the component.
Blazor components can also accept parameters, allowing data to be passed into the component from its parent component. Additionally, components can raise events to communicate with their parent components or other child components.
Overall, Blazor components provide a powerful mechanism for building modular, reusable, and maintainable UIs in Blazor applications, contributing to a more efficient and organized development process. Before we go any further we need to make sure our readers understand how Razor syntax works.
So, what is Razor Syntax (an overview)?
Razor syntax is a combination of HTML and C# or VB.NET code used in the Razor view engine, primarily in ASP.NET Core applications. It allows developers to embed server-side code within HTML markup, making it easier to generate dynamic content in web applications. Razor syntax provides a clean and concise way to write server-side code while maintaining the readability of HTML.
If you are using other frameworks like Flask or Django you probably use to combine HTML with other programming languages. Razor syntax and templating languages like Jinja2 serve similar purposes in their respective web frameworks (ASP.NET Core in the case of Razor and Flask/Django in the case of Jinja2).
1. Inline C# or VB.NET Code
You can embed C# or VB.NET code directly within HTML markup using Razor syntax. Code blocks are delimited by @{ }. For example:
<p>Welcome to the blog, @User.Name!</p>
2. Expression Syntax
You can evaluate C# or VB.NET expressions inline using the @ symbol. Expressions are typically used to output dynamic content within HTML elements. For example:
<p>Total: @TotalAmount</p>
3. Code Blocks
Razor syntax allows you to include code blocks for more complex logic. Code blocks can contain conditional statements, loops, method calls, etc. For example:
@if (myCondition)
{
<p>Result fo Condition is true</p>
}
else
{
<p>Result fo Condition is false</p>
}
4. Layouts
Razor layouts define the overall structure of a web page, including common elements such as headers, footers, and navigation bars. They allow you to define a consistent layout across multiple pages. For example:
@{
Layout = "_Layout";
}
There is more to learn about Razor syntax, you can read more and master it here: Microsoft Dotnet
How to create a component in Blazor?
Blazor components are created as .razor files, which contain both HTML markup and C# code.
A Blazor component typically consists of the following parts:
-
HTML Markup: The visual representation of the component is defined using HTML markup.
-
C# Code Block (@code): C# code associated with the component is placed inside a @code block. This is where you write the logic for the component.
Blazor components can also accept parameters to customize their behavior and appearance. Parameters are declared using @parameter syntax and are passed to the component from its parent component or page. Blazor components can handle user interactions such as clicks, input changes, etc., using event handlers.
Blazor components have lifecycle methods that allow you to perform initialization, cleanup, and other operations at specific points in the component's lifecycle. Some common lifecycle methods, such as: OnInitialized, OnParametersSet, OnAfterRender, OnInitialized{Async}, OnParametersSet{Async}, OnAfterRender{Async}. (More about Blazor Lifecycle Method)
Here's an example of a simple Blazor component I have created:
Let's name the component: LoanPayments.razor
<div class="col-md-8 mt-2">
<div class="card container h-100">
<div class="card-body">
<h2 class="card-title text-center">
Your Monthly Payments
</h2>
<h3 class="card-subtitle mb-2 text-center pt-4" id="monthly-payment">
$@Total.Payment
</h3>
<div class="card-text pt-4">
<div class="row row-cols-2 fw-bold fs-5">
<div class="col">
Total Principal
</div>
<div class="col text-end" id="principal">
$@Total.LoanAmount
</div>
<div class="col">
Total Interest
</div>
<div class="col text-end" id="interest">
$@Total.TotalInterest
</div>
<div class="col">
Total Cost
</div>
<div class="col text-end" id="cost">
$@Total.TotalCost
</div>
</div>
</div>
</div>
</div>
</div>
@code {
[Parameter, EditorRequired]
public Loan? Total { get; set; }
}
The Loan model is looking like the following (Loan.cs):
public class Loan
{
// the amount of the loan
public double LoanAmount { get; set; }
[Range(0.0, 100, MinimumIsExclusive = true, ErrorMessage = "Interest rate must be between 0 and 100")]
// the interest
[Required]
public double Rate { get; set; }
// express in years
[Required]
public int Term { get; set; }
//the montly payment
public double Payment { get; set; }
public double TotalInterest { get; set; }
// total cost of the loan
public double TotalCost { get; set; }
}
As you can see, there are two parts:
- The HTML Markup: In the HTML Markup you find usual HTML tag whit some Bootstrap for styling purpose.
- The C# Code Block: In the C# code Block we define the parameter we want to use inside the HTML markup.
This Blazor component is responsible for displaying information about monthly payments for a loan.
-
[Parameter, EditorRequired] The Parameter attribute is used to tell Blazor that Total can be use as a parameter, and the EditorRequired attribute indicates that the parameter is required for the component to function properly.
-
public Loan? Total { get; set; }: declares a parameter named Total, representing a Loan object. The Loan type is a custom class defined elsewhere in the application, in this case in my Models folder. By the way, the exclamation mark ? you see after the Loan object (Loan?) is to say that the loan object can be null.
Inside the HTML markup we are using the Total parameter to display information the the user, such as: @Total.Payment, @Total.LoanAmount, @Total.TotalInterest, and @Total.TotalCost.
Finally, to reuse this component all we have to do is to get the component name, in this case: LoanPayments, and the paramenter name (Total):
<LoanPayments Total="@payments" />
The @payments is just and example of what I want to display to the user.
Conclusion
Blazor components are the building blocks of Blazor applications, allowing you to create reusable and interactive user interfaces using C# and .NET. By understanding how to create components, use parameters, handle events, and utilize lifecycle methods, you can build powerful and maintainable web applications with Blazor. Hope this explanation helps a little bit in your Blazor journey. Thank you for your time.
Sin comentarios