...

/

Using Layouts and Shared Components

Using Layouts and Shared Components

Learn how to apply layouts and reusable files in Razor components.

In this lesson, we will cover the usage of layouts and shared components in Blazor. Layouts provide a common page template that Razor components are inserted into. Shared Razor components can be used in any Razor component inside the application.

Press + to interact
Razor component layout with page placeholder
Razor component layout with page placeholder

We will use the following project setup. It contains sufficient examples to demonstrate the concepts.

<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>
Blazor WebAssembly project

Razor component layouts

In the above setup, we have one example of a Razor component layout. It is represented by the MainLayout.razor file in the Shared folder of the project.

In Blazor, a layout component is a Razor component that inherits from the LayoutComponentBase class. This is why we have the @inherits directive on line 1 of the MainLayout.razor file.

Press + to interact
@inherits LayoutComponentBase
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<article class="content px-4">
@Body
</article>
</main>
</div>

The ...