Blazor

Creating Blazor Component Libraries

Post valid for: Blazor 0.3.0
Please remember that Blazor is an experimental project and is going to be changing regularly. IT IS NOT PRODUCTION READY.


What are component libraries?

With the release of Blazor 0.2.0 came the ability to create component libraries. Component libraries are how you can share components or JS interop functionality between projects. You can also generate nuget packages from a component library and share via nuget.org.

This is achieved with the introduction of a new project template, Blazor Library. However, at this time the template can only be generated via the dotnet cli and not via Add > New Project in Visual Studio.

I jumped on this feature as soon as Blazor 0.2.0 was released and created my first ever nuget package, BlazoredLocalStorage. This a small, simple library which gives access to the browsers local storage API in your Blazor apps. So if you're in need of access to local storage in your Blazor app please give it a go. If you're interested in the source code it's on my GitHub.

Now I've shamelessly plugged my one and only nuget package, lets look at how to build a reusable component. As an example we're going to create a simple in memory list component. Which will look like this when we're done.

Simple List Blazor Component

Full source code can be found on the blazor-component-libraries repo on my GitHub.

Getting Setup

If you need to get Blazor installed on your system please checkout my earlier post here which covers how to get Blazor installed.

The first thing we need to do is create a new blazor project.

New Blazor Project 1
New Blazor Project 2

Once that is done, open your command line of choice and navigate to the solution directory.

Navigate To Solution Folder

From here we are going to create a new directory for our component library project to live, then move into it.

mkdir SharedComponents
cd SharedComponents

Then run the following command using the dotnet cli tool.

dotnet new blazorlib

This command is going to create us a Blazor Library project using the name of the folder we created above, SharedComponents. If you want to specify a different name you can use the -n yourprojectname option. To see all available options run dotnet new --help.

If you get an error running the above command, check you have the latest Blazor templates installed by running the following command.

dotnet new -i Microsoft.AspNetCore.Blazor.Templates

Now we've created our component library we just need to add it to our solution which I'm going to do back in Visual Studio but you could use the dotnet CLI if you wish.

Select Add Existing Project

Once that has been added your solution should look something like this.

Solution

Creating the Simple List Component

Before we start creating our shared component first delete Component1.cshtml and ExampleJsInterop.cs as well as everything in the content folder.

Now we have a clean base lets start by adding a new Razor View. Right click on the project and select Add > New Item or Ctrl+Shift+A. Call it SimpleList.cshtml.

Be sure to select Razor View and not Razor Page as a Razor page has a code behind which will not work with Blazor.

You can then add the following code to SimpleList.cshtml.

<div class="simple-list">

    <div class="simple-list-header">
        <h1>Simple List</h1>

        <input bind="@newItem" placeholder="Enter item to add to list" />
        <button onclick="@AddItem">Add Item</button>
    </div>

    <div class="simple-list-list">

        @if (!listItems.Any())
        {
            <p>You have no items in your list</p>
        }
        else
        {
            <ul>
                @foreach (var item in listItems)
                {
                    <li>@item</li>
                }
            </ul>
        }
    </div>

</div>


@functions {

    private List<string> listItems = new List<string>();
    private string newItem;

    private void AddItem()
    {
        if (string.IsNullOrEmpty(newItem))
            return;

        listItems.Add(newItem);
        newItem = "";
    }

}

Now we have defined our component it would be good if we could ship it with a default look and feel. In order to achieve this we are going to add a CSS file called simple-list.css to the content folder of our SharedComponents project.

The content folder in a Blazor library project is similar to the wwwroot folder in a Blazor project. It is where static assets such as JavaScript, CSS or images should be placed. When your shared library is consumed, whatever is placed in this folder will be included in the consuming Blazor projects index.html file.

In our case it means when we use the SimpleList component in the main Blazor project, our simple-list.css file will be injected into the index.html automatically for us.

Once you've created the simple-list.css in the content folder paste in the following css... I hope you like orange!

.simple-list {
    border: 1px solid #bdbdbd;
    width: 450px;
    margin: 0 auto;
}

.simple-list-header {
    padding: 20px;
    background: #ff9800;
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#ff9800',endColorstr='#e65100');
    background: -webkit-linear-gradient(305deg,#ff9800 0%,#e65100 100%);
    background: linear-gradient(145deg,#ff9800 0%,#e65100 100%);
}

    .simple-list-header h1 {
        margin: 0 0 20px 0;
        font-size: 24px;
        font-weight: bold;
        text-align: center;
        color: #ffffff;
    }

.simple-list-header {
    text-align: center;
}

    .simple-list-header input {
        padding: 5px;
        width: 300px;
    }

    .simple-list-header button {
        padding: 5px;
    }

.simple-list-list {
    padding: 20px;
}

.simple-list-list p {
    text-align: center;
    margin-bottom: 0;
    font-style: italic;
    color: #616161;
}

.simple-list-list ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

    .simple-list-list ul li:first-of-type {
        border-top: 1px solid #e0e0e0;
    }

    .simple-list-list ul li {
        padding: 10px 0;
        border-bottom: 1px solid #e0e0e0;
    }

That's it, we've now created our component and styled it. So how do we consume it?

Using Shared Components

As we didn't do this earlier go ahead and add a project reference to the SharedComponents project from your Blazor UI project. Once you've done this open the _ViewImports.cshtml file in the root of the Blazor UI project and add the following line.

@addTagHelper *, SharedComponents

What this line is doing is making the components in our SharedComponents project available to the components in this project, similar to a using statement.

With the tag helper in place all we have to do is add our component to the index.cshtml.

<SimpleList></SimpleList>

You can now run the solution and you should see something like this.

SimpleListComponent

Congratulations! You have successfully created your first shared component.

Wrapping up

This was obviously a very simple example of a reusable component. But the power of this feature is plain to see. This will allow a whole eco system of Blazor specific packages to grow. I'm sure in time there will be packages available for lots of thing such as Bootstrap, Telerik controls, Material UI, etc...

If you've got any questions please ask them in the comments. What would you like to see available as a Blazor componet library?