When to have more than one root components in Blazor?

922 Views Asked by At

In the main method of dotnet core blazor web assembly app there is a WebAssemblyHostBuilder class which builds the host for the blazor application. In that class there is a public property called RootComponentMappingCollection which one can add the root component of blazor application (the components that sets up the routing).

It's possible to add more root components to that collection. I'm curious on why having more than one root components in one app and whats the benefits of having more than one root components, when and in what circumstances it's better to have more than one root components?

2

There are 2 best solutions below

0
On

You get to have 2+ independent routers that react to the same URLs.

For a simple application, consider a site with normal 'user' pages. You could inject an Admin or Developer section in each page by stacking an extra root in the Index.Html.

Something you could also accomplish with an AuthorizeRouteView but as a separate app component it would be a much cleaner and more independent solution.

0
On

Besides what @henk-holterman said, the .Net 6 WebAssembly project template itself makes use of this feature to register an instance of the HeadOutlet component to make PageTitle and HeadContent components work.

If you see the content of Program.cs, will face following lines:

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

In the .Net 5 project template, only the first line is present.