In this lesson, you will learn how to build a reusable Modal component that communicates user decisions back to the parent component using EventCallback.
The Architecture of a Reusable Modal
A modal is essentially an overlay that exists "above" your main UI. To make it reusable, we shouldn't hard-code business logic inside the modal. Instead, we use [Parameter] to receive the content and [Parameter] of type EventCallback to report user actions (like "Confirm" or "Cancel").
When the user interacts with a button in your modal, the modal executes the callback. Because we use EventCallback, the parent component is automatically notified and triggered to re-render, keeping the UI state in sync.
Implementation Example
Consider a Modal.razor component that acts as a wrapper for any content:
@if (IsVisible)
{
<div class="modal-overlay">
<div class="modal-content">
@ChildContent
<button @onclick="OnConfirm">Confirm</button>
<button @onclick="OnCancel">Cancel</button>
</div>
</div>
}
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public EventCallback<bool> OnClose { get; set; }
private async Task OnConfirm() => await OnClose.InvokeAsync(true);
private async Task OnCancel() => await OnClose.InvokeAsync(false);
}
Why EventCallback?
You might wonder why we use EventCallback instead of a standard Action. In Blazor, EventCallback is specifically designed for component communication. When you invoke it, Blazor automatically triggers a re-render of the parent component, ensuring that if your OnClose method changes a property (like setting IsVisible = false), the UI updates immediately without manual calls to StateHasChanged().
To use this, the parent simply defines a method:
<Modal IsVisible="_show" OnClose="HandleResult"> <p>Are you sure?</p> </Modal>
By decoupling the display logic from the action logic, you create a "black box" UI component that can be dropped into any page, knowing exactly how to report the user's intent back to your data layer.
Key Takeaway: Use EventCallback to bridge the gap between your reusable Modal and parent logic, ensuring the UI state updates automatically upon user interaction.