Blazor Components

We can create Blazor components within our Blazor application by simply right mouse clicking on a folder or project in Visual Studio and select Add | Razor Component.

A component derives from Microsoft.AspNetCore.Components.ComponentBase, whether implicitly, such as within a .razor file or explicitly, such as in a C# code file.

Razor component

If we create a .razor file we are already implementing a ComponentBase, but usually without an explicit inherit such as the following

@inherits ComponentBase

With or without this @inherit, we will get a generated file (written to obj\Debug\netstandard2.1\Razor) that is a class which implements the ComponentBase.

We can add code to our .razor file in a @code block, thus combining markup and code within the same file, as per this example

@namespace BlazorApp

<h3>@Text</h3>

@code {
    [Parameter]
    public string Text { get; set; }
}

Separate code and razor files

As alternative to a single .razor file with both markup and code, we can create a .cs file for our code. For example if our .razor file is MyComponent.razor we could create a MyComponent.cs and put our code into a C# class. The class should derive from ComponentBase and also be partial

Hence now we have a MyComponent.razor file that looks like this

@namespace BlazorApp

<h3>@Text</h3>

and a C# file, MyComponent.cs that looks like this

using Microsoft.AspNetCore.Components;

namespace BlazorApp
{
    public partial class MyComponent : ComponentBase
    {
        [Parameter]
        public string Text { get; set; }
    }
}

Ofcourse the use of the partial keyword is the key to this working. If we name the file MyComponent.cs all will be fine, but if we name the file MyComponent.razor.cs the file will appear like a code-behind file in other C# scenarios.

Code only component

We could also write a code only component, so let’s assume we have only a MyComponent.cs file

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;

namespace BlazorApp
{
    public class MyComponent : ComponentBase
    {
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            builder.OpenElement(1, "h3");
            builder.AddContent(2, Text);
            builder.CloseElement();
        }

        [Parameter]
        public string Text { get; set; }
    }
}

Obviously we have to put a little bit of effort into constructing the elements in the BuildRenderTree method, but this might suit some scenarios.

Pages and Layouts

Pages and Layouts are just components, just like those discussed above.

The only difference of between a Page and component is that our class is annotated with a PageAttribute for Page. Obviously in a .razor file this happens automatically when we add a page declaration as below

@page "/"

As for the layout, we inherit from LayoutComponentBase, in a .razor file this looks like this

@inherits LayoutComponentBase