Razor Syntax & Component Fundamentals
6 min read
Razor Syntax & Component Fundamentals
Welcome back, C# wizard! π§ββοΈ
If you are reading this, you have likely survived the "Hello World" setup. Now, we are diving into the meat and potatoes of Blazor. If Blazor were a sandwich, Razor would be the bread holding everything together, and Components would be the delicious fillings.
In this module, we are going to stop writing code that looks like a tangled ball of Christmas lights and start building structured, reusable, and beautiful UI elements.
1. Mixing HTML and C#: Mastering the Razor Syntax πͺ
The Problem: The "String Soup" Nightmare
Before modern templating engines, generating dynamic HTML in C# often looked like this:
// The Dark Ages
string html = "<div class='user'>" + user.Name + "</div>";
if(user.IsAdmin) {
html += "<button>Delete World</button>";
}This is awful. It's prone to typos, lacks syntax highlighting, and makes you want to cry.
The Solution: Razor
Razor is a markup syntax that lets you embed C# code directly into HTML. It is not a new language; it is a transition mechanism. It tells the compiler: "Hey, stop reading HTML for a second, I need to do some C# logic here, then go back to HTML."
The Magic Character: @
The @ symbol is your gateway. It transitions from HTML to C#.
1. Implicit Expressions
You don't need to tell Razor when the C# ends; it figures it out based on spaces or HTML tags.
<!-- Calculates 2 + 2 and renders "4" -->
<p>The sum is: @(2 + 2)</p>
<!-- Renders the variable value -->
<h1>Hello, @currentUserName!</h1>2. Control Structures (Loops and Ifs)
We don't use ng-repeat or v-for here. We use C#.
Conditionals:
@if (inventoryCount == 0)
{
<p class="text-danger">Out of Stock! π±</p>
}
else
{
<p>Available: @inventoryCount</p>
}Loops:
<ul>
@foreach (var task in todoList)
{
<!-- The @task.Title is C# inside HTML inside C#... Inception! -->
<li>@task.Title</li>
}
</ul>The @code Block
This is where your logic lives. In a standard .razor file, you usually keep the HTML at the top and the logic at the bottom.
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>
@code {
// This is pure C# class logic
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}Industry Tip: While you can put complex logic inside
@ifblocks in your HTML, don't. Keep your markup clean. If you have a complex condition, create aboolproperty in the@codeblock (e.g.,bool ShouldShowBanner => User.IsLoggedIn && !User.HasPremium;) and use that instead.
2. Creating Your First Custom Component π§©
The Problem: Copy-Paste Fatigue
Imagine you have a specific button style in your app: Blue background, rounded corners, and a specific shadow. You need this button on 20 different pages.
If you copy-paste the HTML <button class="btn btn-blue rounded shadow">...</button> 20 times, and then your designer says, "Make them red," you have to edit 20 files.
The Solution: Reusable Components
In Blazor, everything is a component. A page is a component. A button is a component. A form is a component.
Step-by-Step: The UserProfile Component
Create the File: Create a new file named
UserProfile.razor.- Rule: File names must be PascalCase.
userProfile.razorwill fail to build. Blazor is strict about this.
- Rule: File names must be PascalCase.
Define the UI (HTML):
razor<!-- UserProfile.razor --> <div class="card"> <h3>@Title</h3> <p>Name: @Name</p> </div>Define the API (Parameters):
How do we pass data into this component? We use the[Parameter]attribute.razor@code { // [Parameter] makes this property accessible from the parent [Parameter] public string Title { get; set; } = "Employee"; // Default value [Parameter] public string Name { get; set; } }Use It:
Go to any other page (likeHome.razor) and use it like an HTML tag.razor<!-- Home.razor --> <h1>Welcome to the Team</h1> <UserProfile Title="Manager" Name="Michael Scott" /> <UserProfile Title="Sales" Name="Jim Halpert" />
Fun Fact: When you compile your app, Blazor actually turns your .razor files into C# classes. UserProfile.razor becomes class UserProfile : ComponentBase. You are literally writing classes using HTML syntax.
3. Component Composition: Nesting Components ποΈ
The Problem: The "God Object"
You are building a Dashboard. It has a Navbar, a Sidebar, a Footer, a Chart, and a Data Grid. If you write all of that in Dashboard.razor, you will end up with 3,000 lines of code. Scrolling through that causes repetitive strain injury.
The Solution: Nesting (Parent/Child)
You break the UI down. The Dashboard is the Parent, and the Navbar, Sidebar, etc., are Children.
Passing Content: RenderFragment
Sometimes you don't just want to pass a string (like Name="Jim"). You want to pass HTML or other components inside your component. This is often called "Transclusion" or "Slots" in other frameworks.
Example: A Reusable Alert Box
Child Component (
Alert.razor):razor<div class="alert alert-warning"> <!-- @ChildContent is a reserved name for the inner content --> @ChildContent </div> @code { [Parameter] public RenderFragment ChildContent { get; set; } }Parent Component Usage:
razor<Alert> <!-- Everything inside here is the ChildContent --> <strong>Warning!</strong> The server is <em>literally</em> on fire. π₯ </Alert>
Industry Tip:
RenderFragmentis the secret sauce for layout components (like Cards, Modals, and Accordions). It keeps your UI generic and flexible.
4. The Component Lifecycle: Init, Render, and Dispose β»οΈ
The Problem: Timing is Everything
You can't display user data before you fetch it from the database. You also can't leave a timer running after the user leaves the page (that causes memory leaks, which are the software equivalent of leaving the faucet running).
The Solution: Lifecycle Methods
Blazor gives you specific methods to "hook" into the life of a component.
1. OnInitializedAsync (The Birth)
This runs once when the component is first created. This is where you fetch data.
protected override async Task OnInitializedAsync()
{
// Simulate fetching data
users = await UserService.GetUsersAsync();
}Why Async? Because in the real world, databases are slow. You don't want to freeze the browser while waiting.
2. OnParametersSetAsync (The Update)
This runs whenever the parent component updates the parameters passed to this component.
Scenario: You are viewing Product/1. You click Product/2. The component doesn't destroy and recreate; it just updates the Parameter. OnInitialized won't run again, but OnParametersSet will.
3. Dispose (The Death)
This runs when the component is removed from the UI (user navigated away).
Requirement: Implement IDisposable.
@implements IDisposable
@code {
public void Dispose()
{
// Unsubscribe from events to prevent memory leaks
StateContainer.OnChange -= StateHasChanged;
Console.WriteLine("I have been disposed. Goodbye cruel world! π");
}
}π Under the Hood: The Render Tree
When you update a counter, Blazor doesn't replace the whole HTML page. It calculates the difference (diff) between the old "Render Tree" and the new one, and applies only those changes to the DOM. This is why Blazor is fast.
π Summary Check
- Razor uses
@to switch from HTML to C#. - Components are
.razorfiles (PascalCase required). - Parameters pass data down; RenderFragments pass HTML content down.
- OnInitializedAsync is for loading data.
- Dispose is for cleaning up.
Now, go forth and componentize your world! π
π References & Further Reading
Challenge
Your task is to implement a JavaScript function called groupByProperty. This function will take two arguments:
objectsArray: An array of objects.property: A string representing the name of a property that exists on the objects in the array.
The function should group the objects in the input array based on the value of the specified property. You must use the Array.prototype.reduce() method to accomplish this.
The function should return a new object where each key is a unique value of the specified property, and the corresponding value is an array of all objects from the original array that have that property value.
Expected result
Your function should return an object containing the grouped items. For example, if you call groupByProperty(data, 'category') with the provided data array, the returned object should look like this:
{
"fruit": [
{ "id": 1, "category": "fruit", "name": "apple" },
{ "id": 3, "category": "fruit", "name": "banana" },
{ "id": 6, "category": "fruit", "name": "orange" }
],
"vegetable": [
{ "id": 2, "category": "vegetable", "name": "carrot" },
{ "id": 5, "category": "vegetable", "name": "broccoli" }
],
"dairy": [
{ "id": 4, "category": "dairy", "name": "milk" }
]
}