Using Blazor Components

August 25, 2019

Imagine that you’re writing a Blazor application - maybe it’s similar to this one. Now, imagine that you have a large chunk of HTML in your main view. You might think: I wish I was using React, then I could separate this into its own component.

You can also do this in Blazor. Here’s how.

Components in Blazor

Let’s start with moving your code. The first step is to cut your HTML and paste it into a new Razor Component:

razor components

The format of your new component, from scratch, will be:

[code lang=“HTML”] <h3>Component Name</h3>

@code {

}




Your existing code should go beneath, or instead of:  


<h3>Component Name<h3>




# Parameters

The @code section allows you to put all kinds of crazy C# code in a code behind type model - so you probably don't want to use that, except for passing parameters; for example:



``` csharp


@code {
    [Parameter]
    private string MyParameter { get; set; }
}

This allows you to pass a string into your component; for example (in your main view):

[code lang=“HTML”] <MyComponent MyParameter=“test” />




# Complex Parameters

So far so good.  But what if you need a complex type?  You could, for example, pass a [View Model](https://www.pmichaels.net/2019/07/07/using-view-models-in-blazor/) into your component:



``` csharp


[Parameter]
private MyViewModel MyViewModel { get; set; }

You can pass this into the component as though it were a primitive type:

[code lang=“HTML”] <MyComponent MyViewModel=“@MyViewModel” />




This means that you can lift and shift the code with no changes.  

# Using External Namespaces

As with standard C#, you can access anything within the current namespace.  Should you need any classes that are not in your current namespace, you can declare them at the top of the file, like this:

[code lang="HTML"]
@using MVVMShirt

&lt;h3&gt;My Component&lt;/h3&gt;

Summary

Blazor is still in its infancy, but hopefully, adding actual code to these @code sections will become as frowned upon as code-behind.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024