Lesson 5 of 10
Reusable Components, Parameters, and EventCallback
Break your UI into reusable components and communicate with parameters and EventCallback.
One of Blazor's biggest strengths is component reuse. Instead of building a large page in one file, create small components that receive data through parameters and send events back to their parent.
1. Create StudentCard.razor
Create a folder named Components/Shared, then add StudentCard.razor:
<div class="card p-3 mb-3">
<h4>@Name</h4>
<p>Course: @Course</p>
<p>Level: @Level</p>
<button class="btn btn-outline-primary"
@onclick="SelectStudent">
Select
</button>
</div>
@code {
[Parameter]
public string Name { get; set; } = "";
[Parameter]
public string Course { get; set; } = "";
[Parameter]
public string Level { get; set; } = "";
[Parameter]
public EventCallback<string> OnSelected { get; set; }
private async Task SelectStudent()
{
await OnSelected.InvokeAsync(Name);
}
}
2. Use the component from a page
Create Components/Pages/StudentCards.razor:
@page "/student-cards"
<h1>Student Cards</h1>
<StudentCard Name="Alice Tan"
Course="Computer Science"
Level="Year 2"
OnSelected="HandleSelected" />
<StudentCard Name="John Lee"
Course="Software Engineering"
Level="Year 3"
OnSelected="HandleSelected" />
<p>@message</p>
@code {
private string message = "Select a student.";
private void HandleSelected(string name)
{
message = $"You selected {name}.";
}
}
3. How parent and child communicate
- Parameters send values from parent to child.
- EventCallback lets the child notify the parent that something happened.
- This pattern keeps components reusable and avoids tightly coupling them to one page.
Try it yourself
Add an Email parameter to StudentCard and display it under the course name.