MSDN Documentation

Microsoft Developer Network

Understanding Blazor Components

Blazor components are reusable UI elements that encapsulate markup, logic, and styles. They are the fundamental building blocks of Blazor applications.

What is a Blazor Component?

A Blazor component is a .NET class that inherits from Microsoft.AspNetCore.Components.ComponentBase. Components define their UI using Razor syntax, which blends HTML markup with C# code.

Key Characteristics:

Creating Your First Component

Let's create a simple component named Greeting.razor:

<p>Hello, @Name!</p>

@code {
    [Parameter]
    public string Name { get; set; } = "World";
}

In this example:

Component Parameters

Parameters enable you to pass data into a component. They are defined as public properties decorated with the [Parameter] attribute.

public class UserProfile : ComponentBase
{
    [Parameter]
    public string UserName { get; set; }

    [Parameter]
    public int UserAge { get; set; }

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        // ... component rendering logic ...
    }
}

To use this component and pass parameters:

<UserProfile UserName="Alice" UserAge="30" />

Component Lifecycle

Components have a lifecycle that includes methods called at various stages of their existence. Key methods include:

Note: For detailed information on the component lifecycle, refer to the Component Lifecycle documentation.

Handling Events

Components can raise and handle events to communicate and react to user interactions.

<button @onclick="IncrementCount">Click me</button>
<p>Current count: @currentCount</p>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

The @onclick directive binds the button's click event to the IncrementCount C# method.

Best Practices for Components

Tip: Organize your components into logical folders (e.g., Components/Common, Components/Pages) to maintain a clean project structure.