Lesson 1.5: Using Blazorise Component Library

Components are the basic unit of development in Blazor. A component is a self-contained chunk of user interface (UI), such as a page, dialog, or form. A component includes HTML markup and the processing logic required to inject data or respond to UI events. Components are flexible and lightweight. They can be nested, reused, and shared among projects. Technically, a page is just a set of components with a special directive – @page to work with routing.

Blazor comes with some very basic controls, but there are a lot of third party component libraries that provide more complex controls and encapsulate the behavior of some CSS frameworks. For developers new to HTML and CSS, these libraries make programming the UI easier.

Here are some existing component libraries:

  • Blazored library – set of helpful component libraries, including local storage integration.
  • Blazorise – open source components for Blazor with support for Bootstrap, Bulma, AntDesign and Material CSS frameworks.
  • BlazorStrap – open source Bootstrap 4 components for Blazor.
  • ComponentOne Components – fast datagrid, listview, input and other native Blazor components for server and client-side apps. [paid]
  • DevExpress Components – set of native UI Blazor components (including a Data Grid, Pivot Grid, Scheduler, and Charts). [paid]
  • Telerik UI – native set of UI components for Blazor, including grid, charting, and calendar components. [paid]

After investigating a few different libraries, I decided to use Blazorise because it is open source, free, and well-supported by the community. Blazorise provides a good component abstraction that makes it easy for developers that are not experts in HTML5 and CSS. And Blazorise supports multiple CSS frameworks (in case you need to switch between them). We will be using the Bootstrap CSS framework with Blazorise.

Installing Blazorise NuGet Package

To install component libraries in VS or VS Code, you will need to use the NuGet Package Manager. To launch package manager from the main menu, select View > Other Windows > Package Manager Console. In this console window, you can type:

Install-Package Blazorise.Bootstrap -Version 0.9.1

This will install the current version of the Blazorise library in the current project, and we are going to use the Bootstrap extensions for it. You can also see the installed NuGet packages by launching the NuGet UI… right click on the project (SimpleRPG.Game) and select Manage NuGet Packages in the context menu. You should get the following window (note: that Blazorise.Bootstrap is installed):

Fig 1 – NuGet Package Manager

You can find more details on how to use NuGet Package Manager here: https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio.

Now that we have Blazorise installed. There are a couple of tasks that we need to do to get it integrated into our codebase. Unfortunately as of writing this series, Blazorise doesn’t have a project template to start from, so we need to make these changes by hand. Luckily, the changes are well documented on their GitHub page.

1. Including CSS and Javascript Files

The first step is to find the index.html file (in /wwwroot/index.html) and include the CSS and JS source files from Blazorise:

    <!-- inside of head section -->
    <!-- Begin: Blazorise required css files -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css">
    <link href="_content/Blazorise/blazorise.css" rel="stylesheet" />
    <link href="_content/Blazorise.Bootstrap/blazorise.bootstrap.css" rel="stylesheet" />
    <!-- End: Blazorise required css files -->

...

    <!-- inside of body section and after the <app> tag  -->
    <!-- Begin: Blazorise required script files -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

    <script src="_content/Blazorise/blazorise.js"></script>
    <script src="_content/Blazorise.Bootstrap/blazorise.bootstrap.js"></script>
    <!-- End: Blazorise required script files -->

If you would like to see the full final file, please look in our DevOps repository.

2. _Imports Using

The _Imports.razor file is for developer convenience. This file is implicitly included in all other razor files, so any @using directive added here will be available in any razor file. The _Imports file reduces the duplication of @using directives through our razor codebase. So, let’s add the Blazorise namespace to it the end of the file:

@using Blazorise

3. Program.cs Updates

The program.cs file contains the application’s main entry point. The code in this file sets up the following:

  • The App component, which is the root component of the app, is specified as the app DOM element to the Add method.
  • Services can be configured with the ConfigureServices method on the host builder (for example, builder.Services.AddSingleton<IMyDependency, MyDependency>();).
    • These services are available throughout the app via Blazor Dependency Injection. We will cover that in the future.
  • Configuration can be supplied via the host builder (builder.Configuration).

Let’s update the code in this file to the following:

using Blazorise;
using Blazorise.Bootstrap;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace SimpleRPG.Game
{
    /// <summary>
    /// Main program class.
    /// </summary>
    public sealed class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.Services
              .AddBlazorise(options =>
              {
                  options.ChangeTextOnKeyPress = false;
              })
              .AddBootstrapProviders();

            builder.RootComponents.Add<App>("app");
            builder.Services.AddTransient(sp => new HttpClient
            {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            var host = builder.Build();

            host.Services
              .UseBootstrapProviders();

            await host.RunAsync().ConfigureAwait(false);
        }
    }
}

This now includes using references to Blazorize, setting up the Blazorise services (.AddBlazorise), and configuring the Blazorise Bootstrap provider (.UseBootstrpProviders).

I know this is a lot of boilerplate setup, but once it’s going it will make our development lives easier.

Use the Blazorise Components

Finally, let’s use a couple Blazorise components to ensure everything is working as expected. Notice that our Index.razor page initially looks like this:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

Rather than using the direct HTML tags, let’s use a couple of Blazorise components <Heading> and <Text>. These provide developer friendly extensions around the HTML header and span tags. The new code is:

@page "/"

<Heading Size="HeadingSize.Is1">Hello, world!</Heading>

<Text>Welcome to your new app.</Text>
<Alert Color="Color.Info" Visible="true">Now using Blazorise!!!</Alert>

Notice: how we are using the component notation rather than HTML tags and CSS, and these components have properties that expose interesting capabilities like Size, Color, and Visibility. Behind the scenes, Blazorise components render themselves in HTML and CSS with classes and styles based on the component properties. There is a ton to learn in the Blazorise library. We will be describing its components as we use them in our game. But if you want to develop a deeper understanding of the power and richness of Blazorise, please check out the Blazorise documentation site.

Also it is possible to use both direct HTML/CSS and Blazorise components on the same page. We will be doing that in future lessons.

Now, let’s build and run our application (Ctrl + F5) to see this all in action:

Fig 2 – Simple home page with Blazorise

We’ve come to another good stopping point. Let’s commit our current changes to Git again, so we can proceed to the next step.

Note: if you need the instructions again for committing, review the previous lesson.

2 thoughts on “Lesson 1.5: Using Blazorise Component Library

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s