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:
- Reusable: Design components once and use them across your application.
- Encapsulated: Components manage their own state and UI, promoting modularity.
- Composable: Build complex UIs by nesting components within each other.
- Razor Syntax: Uses a combination of HTML and C# for defining UI and logic.
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:
- The
.razor
file contains HTML markup and C# code. @Name
is a C# expression that will be rendered into the HTML.- The
@code
block contains C# code. [Parameter]
attribute allows the component to receive data from its parent.
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:
OnInitialized()
: Called when the component is initialized.OnParametersSet()
: Called after component parameters are initialized or updated.OnAfterRender(bool firstRender)
: Called after the component has been rendered to the DOM.
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
- Keep components small and focused: Each component should have a single responsibility.
- Use parameters for input: Pass data into components via parameters.
- Use event callbacks for output: Use
EventCallback
to notify parent components of events. - Prefer composition over inheritance: Build complex UIs by combining smaller components.
Tip: Organize your components into logical folders (e.g., Components/Common
, Components/Pages
) to maintain a clean project structure.