Course contentsShow
← C#
Lesson 1337 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Dynamic Content Injection

Use RenderFragment to pass templates into components for highly flexible layouts.

In this lesson, you will learn how to use RenderFragment to build highly reusable components that allow parent components to inject custom UI templates dynamically.

The Problem of Static Components

When building UI components, you often find yourself creating wrappers—like a Card or a Modal—that have a fixed structure. If you hardcode the content inside those components, you lose flexibility. You end up creating dozens of variations of the same component just to change a small inner block of HTML.

Introducing RenderFragment

In Blazor, a RenderFragment acts as a delegate that represents a segment of UI. By defining a parameter of type RenderFragment in your component, you create a "slot" where the parent can inject any arbitrary HTML or other components.

Consider a Card.razor component:

<div class="card">
    <div class="card-header">My Flexible Card</div>
    <div class="card-body">
        @ChildContent
    </div>
</div>

@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

By naming the parameter ChildContent, Blazor treats it as the default container for any content placed between the component's opening and closing tags.

Usage in the Parent

Now, when you use the Card component in a page, you don't need to worry about its internal layout; you simply provide the inner content:

<Card>
    <h3>Dynamic Title</h3>
    <p>This paragraph was injected dynamically!</p>
    <button>Click me</button>
</Card>

Why This Matters

This approach decouples your "layout logic" from your "content logic." You can have multiple RenderFragment parameters—such as a Header and Footer fragment—allowing you to create advanced design patterns like complex sidebars or dashboard widgets without ever rewriting the wrapper markup. It keeps your code DRY (Don't Repeat Yourself) while providing maximum flexibility for your UI requirements.

Key Takeaway: Use RenderFragment parameters to create UI "slots" that allow parent components to inject dynamic templates, effectively turning static wrappers into powerful, reusable layout engines.