Learn Blazor Β· 5/15

Component Communication and Parameters

7 min read

Welcome to Topic #5 of the Blazor curriculum! πŸš€

If you thought building a single component was fun, wait until you see them talk to each other. In a real-world application, components are like employees in a company. If they sit in silence and don't share data, nothing gets done.

Today, we are going to learn how to pass data down, send signals up, teleport data through the component tree, and handle messy HTML attributes with grace.


1. Component Parameters: Passing Data from Parent to Child

Definition

Component Parameters are public properties on a Blazor component decorated with the [Parameter] attribute. They allow a parent component to supply data to a child component during rendering.

The Problem

Imagine you are building a UserProfile component.
If you hardcode the name inside the component like <h3>Name: John Doe</h3>, that component is useless for anyone named "Jane." You would need to create a new component for every user in your database. That is... terrible. 0/10. Would not recommend.

The Solution

We expose a "slot" (a property) that allows the parent to inject the name dynamically.

How it Works

  1. In the Child component, define a public property.
  2. Add the [Parameter] attribute.
  3. In the Parent component, set that property via an HTML-style attribute.

πŸ’» The Code

Child Component (UserProfile.razor)

razor
<div class="card">
    <h3>User Profile</h3>
    <p>Name: @UserName</p>
    <p>Role: @Role</p>
</div>

@code {
    // 1. We define the properties
    // 2. We decorate them with [Parameter]
    [Parameter]
    public string UserName { get; set; } = "Guest"; // Default value helps avoid null errors!

    [Parameter]
    public string Role { get; set; }
}

Parent Component (Home.razor)

razor
@page "/"

<h1>Welcome to the Dashboard</h1>

<!-- Passing literal strings -->
<UserProfile UserName="Alice" Role="Admin" />

<!-- Passing dynamic C# variables -->
<UserProfile UserName="@currentUser" Role="@currentRole" />

@code {
    private string currentUser = "Bob";
    private string currentRole = "Editor";
}

🧠 Industry Best Practice

Immutability: Treat parameters as read-only inside the child component.

  • Don't: Change the value of UserName inside UserProfile.razor. It gets confusing because if the parent re-renders, it will overwrite your local changes.
  • Do: If you need to change the data, emit an event to the parent (see the next section) and let the parent change the source of truth.

Fun Fact: If you forget the public keyword or the { get; set; } on your parameter, Blazor will silently ignore it, and you will spend 2 hours debugging why your data isn't showing up. We've all been there. β˜•


2. EventCallbacks: Sending Triggers from Child to Parent

Definition

EventCallback is a specific struct in Blazor designed to expose events from a component. It allows a child to notify the parent that something happened (like a button click) and optionally pass data back.

The Problem

Your UserProfile component has a "Delete User" button.
The UserProfile (Child) handles the UI, but it doesn't own the list of usersβ€”the Parent does. The Child cannot delete the user directly from the Parent's list. It needs to scream, "HEY! DELETE THIS GUY!"

The Solution

The Child exposes an EventCallback. The Parent "subscribes" to this event and decides what to do when it triggers.

How it Works

  1. Child defines a [Parameter] of type EventCallback (or EventCallback<T> if sending data).
  2. Child invokes the callback using .InvokeAsync().
  3. Parent passes a method to that parameter.

πŸ’» The Code

Child Component (DeleteButton.razor)

razor
<button class="btn btn-danger" @onclick="HandleClick">
    Delete User
</button>

@code {
    // The <int> means we are sending an Integer (UserID) back to the parent
    [Parameter]
    public EventCallback<int> OnUserDeleted { get; set; }

    [Parameter]
    public int UserId { get; set; }

    private async Task HandleClick()
    {
        // We invoke the event and send the ID up
        await OnUserDeleted.InvokeAsync(UserId);
    }
}

Parent Component (UserList.razor)

razor
<h3>User List</h3>
<p>@message</p>

<DeleteButton UserId="42" OnUserDeleted="RemoveUser" />

@code {
    private string message = "";

    // This method runs when the child clicks the button
    private void RemoveUser(int id)
    {
        // In real life, you'd delete from DB here
        message = $"User {id} has been yeeted from the system.";
    }
}

🧠 Deep Dive: Why not just use C# Action or Func?

You can pass a standard C# Action as a parameter, but EventCallback is smarter.
When an EventCallback is invoked, Blazor automatically calls StateHasChanged() on the Parent component. This ensures the Parent re-renders to reflect the changes. If you use a plain Action, the parent might not update the UI until you manually force it.


3. Cascading Parameters: Passing Data Deep Down the Tree

Definition

Cascading Parameters allow you to pass data from an ancestor component to any descendant component, regardless of how deep they are in the nesting, without passing it through every layer in between.

The Problem

Prop Drilling (a.k.a Component Inception).
Imagine you have this structure:
MainLayout -> Dashboard -> WidgetGrid -> UserCard -> EditButton.

If MainLayout has a "ThemeColor" (Dark Mode), and EditButton needs to know that color, you normally have to pass the parameter through Dashboard, WidgetGrid, and UserCard, even though they don't care about it. This is tedious and makes your code look like a staircase.

The Solution

Wrap the root in a <CascadingValue>. Any child, grandchild, or great-grandchild can catch it using [CascadingParameter].

πŸ’» The Code

The Ancestor (MainLayout.razor)

razor
<div class="main-layout">
    <!-- We wrap everything inside CascadingValue -->
    <!-- Name is optional but recommended if you have multiple cascades -->
    <CascadingValue Value="@ThemeColor" Name="AppTheme">
        @Body
    </CascadingValue>
</div>

@code {
    public string ThemeColor { get; set; } = "dark-mode";
}

The Great-Grandchild (EditButton.razor)

razor
<button class="btn @AppliedTheme">
    Edit
</button>

@code {
    // We catch the value by matching the Name or Type
    [CascadingParameter(Name = "AppTheme")]
    public string AppliedTheme { get; set; }
}

🧠 Industry Reality Check

Use Cascading Parameters sparingly.

  1. Good use cases: Auth state (is user logged in?), Themes, Current Language/Localization.
  2. Bad use cases: Passing a list of 10,000 items.
  3. Performance: If the CascadingValue changes, every component subscribing to it re-renders. If you cascade a complex object and change one property, you might trigger a UI refresh avalanche.

4. Attribute Splatting and Capturing Unmatched Parameters

Definition

Attribute Splatting is a technique where a component captures all "extra" attributes passed to it (that aren't explicitly defined as Parameters) and applies them to an HTML element inside the component.

The Problem

You create a custom component wrapper, like <MyInput />.
A developer uses it: <MyInput Placeholder="Enter text" />.
You add a [Parameter] public string Placeholder {get;set;}.
Then they want <MyInput Class="form-control" />. You add a parameter.
Then they want <MyInput Style="color:red" />. You add a parameter.
Then they want data-toggle, aria-label, tab-index...
You will spend your whole life writing parameters for standard HTML attributes.

The Solution

Tell Blazor: "Take all the attributes I didn't define specifically, put them in a bag, and splash (splat) them onto this input tag."

How it Works

  1. Create a Dictionary<string, object> property.
  2. Add [Parameter(CaptureUnmatchedValues = true)].
  3. Use @attributes="YourDictionary" on the HTML element.

πŸ’» The Code

The Component (MyFancyInput.razor)

razor
<div class="input-wrapper">
    <label>@Label</label>
    <!-- Here is the magic splat -->
    <input @attributes="InputAttributes" />
</div>

@code {
    [Parameter]
    public string Label { get; set; }

    // This catches class, style, placeholder, data-id, etc.
    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> InputAttributes { get; set; }
}

The Usage (Parent.razor)

razor
<!-- We can now treat MyFancyInput like a normal HTML input -->
<MyFancyInput 
    Label="Email Address" 
    class="form-control bg-light" 
    placeholder="[email protected]" 
    required 
    data-test-id="email-field" />

🚧 Detailed Behavior

If you define class inside the component and pass class from the parent, Blazor is smart enough to merge them for class attributes (mostly), but for others, the splatted attributes (from the parent) usually win (overwrite).


Summary of Communication

Method Direction Best For...
Parameters Parent βž” Child Passing data, configuration, models.
EventCallbacks Child βž” Parent Button clicks, form submissions, notifying changes.
Cascading Ancestor βž” Descendant Themes, Auth State, global context (avoids prop drilling).
Splatting Parent βž” Child HTML Applying CSS classes, styles, and HTML attributes dynamically.

πŸ“š Further Reading & References


Next up: State Management! (Or "How to remember things when the user navigates away"). Stay tuned. πŸš€

Challenge

You are tasked with creating a JavaScript function that simulates fetching data from a server.

Create a function named fetchData that accepts a single argument: an url string.

This function must return a Promise.

Inside the promise's executor function, use a setTimeout to simulate a network delay of 1500 milliseconds.

After the delay, check the provided url:

  • If the url is exactly equal to the string 'https://api.example.com/data', the promise should resolve with the following JSON object: {"status": "success", "data": [1, 2, 3, 4, 5]}.
  • For any other url value, the promise should reject with an Error object constructed with the message 'Invalid URL: Not Found'.

Expected result

Your code should define a function fetchData that returns a promise. This promise should resolve with a specific JSON object for a valid URL or reject with an Error object for an invalid URL, both after a 1.5-second simulated delay.

Example implementation:

javascript
function fetchData(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (url === 'https://api.example.com/data') {
        resolve({ status: 'success', data: [1, 2, 3, 4, 5] });
      } else {
        reject(new Error('Invalid URL: Not Found'));
      }
    }, 1500);
  });
}
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.