In this lesson, you will learn how to create highly reusable "Layout Containers" by leveraging RenderFragment to inject custom content templates and specific slots into your components.
The Power of RenderFragment
In complex applications, you often need components like Cards, Modals, or Data Tables that have a static outer structure but require dynamic internal content. Instead of hardcoding the markup inside your component, you can use RenderFragment properties to act as placeholders or "slots" for the parent component to fill.
By default, any content placed inside a component tag in Razor is assigned to a parameter named ChildContent of type RenderFragment. However, for advanced flexibility, you can define multiple named slots to allow the parent to "stamp" content into specific areas (like a header, footer, or body).
Implementation Pattern
Imagine a Card component that needs a header section and a primary body section. You define the fragments in your component code block:
<div class="card">
<header>@HeaderTemplate</header>
<main>@ChildContent</main>
</div>
@code {
[Parameter] public RenderFragment? HeaderTemplate { get; set; }
[Parameter] public RenderFragment? ChildContent { get; set; }
}
When using this component, the parent developer can now cleanly structure the UI:
<Card>
<HeaderTemplate>
<h3>User Profile</h3>
</HeaderTemplate>
<p>This is the main content rendered into ChildContent.</p>
</Card>
Why Use Named Slots?
This pattern moves beyond simple "nested content" by allowing the component to control the styling and layout of its slots while remaining completely agnostic about the actual content injected. It prevents "prop drilling"—where you would otherwise have to pass dozens of strings or objects just to render a specific visual region. By treating your UI as a collection of composable templates, you reduce code duplication and ensure that structural changes (like changing a div to a section) only need to happen in one place.
Key Takeaway: By defining multiple RenderFragment properties, you transform rigid components into flexible, layout-agnostic containers that allow parent components to inject content into precise structural slots.