Skip to content

Component Communication

Components need to communicate with each other to share data and coordinate actions. Blazor provides several patterns for component communication.

Parent to Child

Parent components can pass data to child components through parameters, enabling a one-way flow of data down the component hierarchy.

razor
@* Parent.razor *@
<ChildComponent Message="Hello from parent" />

@* Child.razor *@
@code {
    [Parameter]
    public string Message { get; set; }
}

Child to Parent

Child components can notify parent components of events or changes using callbacks, allowing data to flow upward in the component tree.

razor
@* Parent.razor *@
<ChildComponent OnEvent="HandleEvent" />

@code {
    private void HandleEvent(string data)
    {
        // Handle the event
    }
}

@* Child.razor *@
@code {
    [Parameter]
    public EventCallback<string> OnEvent { get; set; }
}

Cascading Values

Cascading values allow data to be passed down through multiple levels of components without explicit parameter passing at each level.

razor
<CascadingValue Value="@theme">
    <ChildComponent />
</CascadingValue>

@code {
    private Theme theme = new Theme();
}