DEV Community

Grant Watson
Grant Watson Subscriber

Posted on

Blazor Components

ORIGINAL POST

Blazor Components Basics and Simple Structure:

What are Blazor components?

A Blazor component is an independent part of the Blazor Application. These entities can be as simple or as complex as the application calls for. Blazor applications are made utilizing parts that are adaptable, lightweight, and can be settled, reused, and shared between ventures. A component is the base component of the Blazor application, i.e., each page is considered as a segment in Blazor.

It utilizes the mix of Razor, HTML, and C# code as a part. For example:

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>

@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}
Enter fullscreen mode Exit fullscreen mode

Blazor segments are executed in *.cshtml records utilizing a mix of C# and HTML markup. The UI for a segment is characterized utilizing HTML while dynamic delivering rationale like circles, conditionals, articulations are included utilizing an installed C# language structure called Razor.

In the work square, we can characterize all the properties that are utilized in see markup, and the techniques are bound with control as an occasion.

At the point when a Blazor application is assembled, the HTML markup and C# delivering rationale are changed over into a part class, and the name of the produced class coordinates the name of the record.

Component Members

Individuals from the segment class are characterized in a @functions square, and you can utilize more than one @functions obstruct in a part. In the @functions square, segment states, for example, properties and fields are determined alongside strategies for occasion taking care of or for characterizing other part rationales. Segment individuals would then be able to be utilized as a major aspect of the part's delivering rationale utilizing C# articulations that start with @.

All rendered Blazor views descend from the ComponentBase class, this includes Layouts, Pages, and also Components.

A Blazor page is essentially a component with a @page directive that specifies the URL the browser must navigate to in order for it to be rendered. In fact, if we compare the generated code for a component and a page there is very little difference. The following generated source code can be found in Counter.razor.g.cs in the folder obj\Debug\netcoreapp3.0\Razor\Pages.

namespace SomeBlazorApp.Client.Pages
{
    [Microsoft.AspNetCore.Components.LayoutAttribute(typeof(MainLayout))]
    [Microsoft.AspNetCore.Components.RouteAttribute("/counter")]
    public class Counter : Microsoft.AspNetCore.Components.ComponentBase
    {
        protected override void BuildRenderTree(Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder)
        {
            // Code omitted for simplicity
        }
    private int counter = 42;
    private void IncrementCounter()
    {
        counter++;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

[Microsoft.AspNetCore.Components.RouteAttribute("/counter")] identifies the URL for the page.

[Microsoft.AspNetCore.Components.LayoutAttribute(typeof(MainLayout))] identifies which layout to use.

In fact, because pages are merely components decorated with additional attributes, if you alter the Pages/Index.razor file of a default Blazor app, it is possible to embed the Counter page as a component.

@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<Counter/>
Enter fullscreen mode Exit fullscreen mode

When embedding a page within another page, Blazor treats it as a component. The LayoutAttribute on the embedded page is ignored because Blazor already has an explicit container – the parent component that contains it.

Creating Components

Depending on your hosting service, and whether you chose Blazor WebAssembly or Blazor Server, the following may be ambiguous. But let’s say for simplicity sake, your main solution has 3 projects: Client/Server/Shared.

Under the Client Project:

Make a new folder called Components. This name can be anything that you wish it to be, for it is not a special or “needed” name. Once you have create the folder, create a file within the folder and name it ComponentOne.razor and the following markup is the starting point of any new component:

//Section 1
@page "/"

//Section 2
<h1>
  Hello World!
</h1>

<p>
  Welcome to your component
</p>

//Section 3
@code {
    //empty code block
}
Enter fullscreen mode Exit fullscreen mode

Let’s stop for a quick moment to discuss what each section is. If you have ever worked in ReactJS or Angular, this may look familiar to you, and feel free to go forward. If this is your first time working in a front end framework, let’s go over some basics:

Section 1:
For clarity and simplicity over the structure/architecture of a component, this is where you will post and dictate your using statements for your components. There is a _Import.razor file to where you can place your using statements, but this is beyond the scope of this article. When you need to declare another file from your solution into you component, put them at the top of your component here. This is also where you can call your Nuget packages you specifically want to use in your component.

The next area you see here is the @page “/”

Similar with routing in React, we dictate the routing of this particular component as “/”. Again, routing is outside the scope of this article, I will have another article covering this in the future.

Section 2:
This area should look “easy” to you. Especially if your component is a simple display component. This area is where you place your HTML code inside the component.

Section 3:
This area is the fun part of the component in my opinion. This is where we combine C# syntax into the component itself. May it be service calls, httpClient and JSON calls to APIs. In this code block, you as the developer can make you component perform magic here.

In the next few articles, I will go into more in the depth and breadth of components, and the following is what I am considering covering:

  1. One Way Binding in Components
  2. Two Way Binding in Components
  3. Component Literals, Expressions, and Directives
  4. Browser DOM and Component Events
  5. Cascading Values
  6. Code Generated HTML Attributes
  7. Capturing Unexpected Parameters
  8. Replacing Attributes on child components
  9. Component Lifecycles
  10. Multi-threaded rendering

If there is a topic that you would like for me to cover with Blazor, or any language that you would like to see, please feel free to contact me through email at info@grantwatson.dev or on Twitter @granticusdev

Top comments (0)