Blazor Components

Vaibhav Bhapkar
2 min readJul 4, 2020

In this article, we will explore components in Blazor,

Blazor is a component-driven framework.

Components can be nested, reused, and shared across multiple projects.

Components have a file extension. Razor

Blazor components also called a razor component and component name must start with uppercase otherwise you will get a compile-time error.

When you see the component code there are two sections one is the HTML and other is your C# code as shown below,

@page “/counter”<h1>Counter</h1><p>Current count: @currentCount</p><button class=”btn btn-primary” @onclick=”IncrementCount”>Click me</button>@code {private int currentCount = 0;private void IncrementCount(){currentCount++;}}

In the @code section, you can write your C# logic. For the simple component we can with this approach were both HTML markup and C# are in the same file but for large projects, its good practice to separate HTML markup and C# file we can do this by two approaches called Partial Files and Base Class.

1) Partial File approach:

In this approach, we will keep markup code in HTML file only while for C# code we create a new class named Componentname.razor.cs after creation this file is nested under Componentname.razor to make C# class available to HTML declare that class as partial.

Counter.razor

@page “/counter”<h1>Counter</h1><p>Current count: @currentCount</p><button class=”btn btn-primary” @onclick=”IncrementCount”>Click me</button>

Counter.razor.cs

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace TestApp.Pages{public partial class Counter{private int currentCount = 0;private void IncrementCount(){currentCount++;}}}

2) Base Class

For the base class create a new class file named ComponentnameBase.cs and then for making this class as base class inherit it from ComponentBase class from AspNet.Core.Component. Now for using this base class in component Inherits the declare class in the component.

Counter.razor

@page “/counter”@inherits CounterBase<h1>Counter</h1><p>Current count: @currentCount</p><button class=”btn btn-primary” @onclick=”IncrementCount”>Click me</button>

CounterBase.cs

using Microsoft.AspNetCore.Components;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace TestApp.Pages{public class CounterBase:ComponentBase{protected int currentCount = 0;protected void IncrementCount(){currentCount++;}}}

Thank You, See you in the next article !!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

--

--

Vaibhav Bhapkar

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *