Dynamically Rendered Razor Components
Explore how to dynamically render different Razor components in Blazor using the DynamicComponent feature. Understand how to switch components based on user interaction and pass parameters to customize component content, enhancing flexibility in your web applications.
We'll cover the following...
Blazor allows us to dynamically render elements inside Razor components. This can be achieved by using the built-in DynamicComponent component. This component acts as a placeholder for any other Razor component element and we can change this element dynamically.
To demonstrate how dynamic rendering works, we have the following project setup. In this project, we have added multiple Razor components with different structures. Each of these components represents a specific category of animals. We display one of these components on the home page of our application, where we can dynamically change the component type to display.
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
DynamicComponent overview
The ...