ASP.NET Core Documentation

Components

Blazor components are the fundamental building blocks of Blazor applications. They are reusable pieces of UI, often defined as Razor components (.razor files), that encapsulate rendering logic and event handling.

Creating a Blazor Component

A Blazor component is typically defined in a file with a .razor extension. This file combines HTML markup for the UI with C# code for logic and event handling.

Example: A Simple Counter Component


@page "/counter"

Counter

Current count: @currentCount

@code { private int currentCount = 0; private void IncrementCount() { currentCount++; } }

Component Structure

A Razor component consists of:

Component Parameters

Components can accept input parameters using the [Parameter] attribute. This allows for data to be passed from parent components to child components.

Example: Component with Parameters


@* ParentComponent.razor *@
<h3>Welcome, @userName!</h3>
<GreetingMessage Message="Hello from parent!" User="Alice" />

@code {
    private string userName = "Alice";
}

@* GreetingMessage.razor *@
<div>
    <p>@Message</p>
    <p>User: @User</p>
</div>

@code {
    [Parameter]
    public string Message { get; set; }

    [Parameter]
    public string User { get; set; }
}
            

Component Lifecycle

Blazor components have a defined lifecycle, with methods that are called at various stages (e.g., initialization, rendering, disposal). This allows you to hook into specific moments to perform actions.

Key lifecycle methods include:

Refer to the Component Lifecycle documentation for more details.

Component Cascading Values

Cascading values allow you to pass data down through the component tree without explicitly passing it as parameters at each level. This is useful for themes, authentication status, or configuration.

For more in-depth information, explore the Hosting Models and Data Binding sections.