Creating a Blazor Component
This tutorial guides you through the fundamental process of creating reusable UI components in Blazor.
Blazor components are the building blocks of your web application. They are reusable pieces of UI that encapsulate their own markup, styling, and behavior. Understanding how to create and use components is essential for building scalable and maintainable Blazor applications.
Understanding Component Structure
A Blazor component is typically defined by a Razor file (.razor
). This file combines HTML markup with C# code to define the component's behavior and rendering logic.
Example: A Simple Button Component
Let's start with a basic button component. Create a new file named SimpleButton.razor
in a Components
folder within your Blazor project.
@* SimpleButton.razor *@
<button class="simple-btn" @onclick="HandleClick">
@ButtonText
</button>
@code {
[Parameter]
public string ButtonText { get; set; } = "Click Me";
[Parameter]
public EventCallback OnClick { get; set; }
private void HandleClick()
{
if (OnClick.HasDelegate)
{
OnClick.InvokeAsync();
}
}
}
Explanation:
@buttonText
: This is a parameter that allows you to customize the text displayed on the button from where the component is used. The[Parameter]
attribute makes it accessible for binding.@onclick="HandleClick"
: This event handler binds the button's click event to theHandleClick
method.@code { ... }
: This block contains the C# code for the component, including properties and methods.EventCallback
: This is a Blazor-specific type for handling events. It allows the parent component to subscribe to events raised by this component.
Using the Component
To use the SimpleButton
component, you can include it in another Razor file, such as Index.razor
:
@page "/"
<h1>Welcome to My App</h1>
<p>Here's a custom button:</p>
<SimpleButton ButtonText="Learn More" OnClick="NavigateToDocs" />
<p>And another one:</p>
<SimpleButton /> @* Uses default text "Click Me" *@
@code {
private void NavigateToDocs()
{
Console.WriteLine("Navigating to documentation...");
// In a real app, you'd use NavigationManager to navigate.
// navigationManager.NavigateTo("/docs");
}
}
Explanation:
<SimpleButton ButtonText="Learn More" OnClick="NavigateToDocs" />
: This line renders an instance of theSimpleButton
component. We pass a custom value for theButtonText
parameter and bind the component'sOnClick
event to theNavigateToDocs
method in the parent component.<SimpleButton />
: This renders another instance, using the defaultButtonText
value.
Component Lifecycle
Blazor components have a lifecycle that dictates when and how they are initialized, rendered, and updated. Key lifecycle methods include:
OnInitialized()
: Called when the component is initialized.OnParametersSet()
: Called afterOnInitialized()
and after each parameter is set.ShouldRender()
: Allows you to control whether the component should re-render.OnAfterRender()
: Called after the component has been rendered to the DOM.
Passing Complex Data
You can pass complex data types, including collections and other component instances, as parameters. You can also define child content using RenderFragment
.
Example: Component with Child Content
@* Card.razor *@
<div class="card">
<div class="card-header">
<h3>@Title</h3>
</div>
<div class="card-body">
@ChildContent
</div>
</div>
@code {
[Parameter]
public string Title { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
}
@* In another component, e.g., Index.razor *@
<Card Title="My Card">
<p>This is the content inside the card.</p>
<button>Action</button>
</Card>
RenderFragment
allows for powerful composition, enabling you to pass arbitrary HTML or other components as content.
Styling Components
Components can have their own scoped CSS using a .razor.css
file (e.g., SimpleButton.razor.css
). This helps prevent style conflicts between components.
@* SimpleButton.razor.css *@
.simple-btn {
background-color: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s ease;
}
.simple-btn:hover {
background-color: #2980b9;
}
Next Steps
Now that you understand the basics of creating Blazor components, you can explore more advanced topics such as:
- Component state management
- Data binding and forms
- Component composition patterns
- Integrating with JavaScript