DEV Community

Paul Michaels
Paul Michaels

Posted on • Originally published at pmichaels.net

Using Blazor Components

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:

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

    <h3>Component Name</h3>

    @code {

    }
Enter fullscreen mode Exit fullscreen mode

Your existing code should go beneath, or instead of:

<h3>Component Name</h3>
Enter fullscreen mode Exit fullscreen mode

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:

@code {
    [Parameter]
    private string MyParameter { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

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

<MyComponent MyParameter="test" />
Enter fullscreen mode Exit fullscreen mode

Complex Parameters

So far so good. But what if you need a complex type? You could, for example, pass a View Model into your component:

[Parameter]
private MyViewModel MyViewModel { get; set; }
Enter fullscreen mode Exit fullscreen mode

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

<MyComponent MyViewModel="@MyViewModel" />
Enter fullscreen mode Exit fullscreen mode

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:

@using MVVMShirt

<h3>My Component</h3>
Enter fullscreen mode Exit fullscreen mode

Summary

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

Top comments (0)