Skip to content

Introduction to Blazor Components

Components are the fundamental building blocks of Blazor applications. They are self-contained pieces of user interface (UI) that can be reused throughout your application.

What are Components?

Components in Blazor are:

  • Reusable UI elements
  • Implemented using Razor syntax (.razor files)
  • Can include HTML, CSS, and C# code
  • Can be nested and composed
  • Support parameters and events
  • Have their own lifecycle

Basic Component Structure

razor
@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++;
    }
}

Component Features

  • Isolation: Components have their own state and behavior
  • Reusability: Can be used multiple times in different parts of your application
  • Composability: Can be composed of other components
  • Parameters: Accept input through parameters
  • Events: Can raise and handle events
  • Lifecycle: Have a defined lifecycle for initialization and cleanup