So you’re building an app that needs charts, and you want to use a well-supported chart library like Chart.js, but you’re building your app using Blazor. How do you avoid having to do lots of Javascript interop?

Well, first let me say well done for picking Blazor. It’s a fantastic Single Page Application framework allowing you to stay in the world of C# whilst making Javascript something of a second-class citizen. As C# is my main programming language, this is perfect for me!

Avoiding Javascript Interop

To answer the question of how we avoid Js interop, there is a solution, and it comes in the form of an open-source project by mariusmuntean. Marius has created a fantastic library called ChartJs.Blazor, which is a wrapper around ChartJs that allows you to configure and render the same charts in a Blazor app without writing Javascript. Let’s take a look at you could use this library to build beautiful charts for your Blazor app.

Pre-Requisites

According to the documentation for ChartJs.Blazor, the library requires an IDE which supports Blazor and a minimum .NET version of Core 3. So if you’re using .NET Core 3 all the way up to .NET 8 preview (latest at the time of writing), you’re all good.

IDEs that fit into this category would be Visual Studio (Mac/Windows) and JetBrains Rider. My preference is Rider but it’s really down to personal choice.

Installing ChartJs.Blazor

The library can be installed via as a package via NuGet. I wouldn’t recommend forking the project and compiling the source code unless you specifically needed to customise it.

Open the package manager in your IDE and type the following command to install the package:

dotnet add package ChartJs.Blazor.Fork

You can also search for ChartJs.Blazor.Fork in your package manager’s GUI.

A picture showing the GUI of NuGet Package manager in JetBrains rider, with a search for ChartJs.Blazor.Fork

Adding Dependencies

While the library does allow us to avoid writing lots of Javascript, we still need to add these references to Js script files.

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>


<script src="_content/ChartJs.Blazor.Fork/ChartJsBlazorInterop.js"></script>

Blazor has two project types, server-side, and webassembly. Depending on which version you’re using, you’ll need to add the above references to different places.

Server-Side Blazor

Add the references to the _Layout.cshtml page, just under the reference to blazor.server.js. in the body tag.

Blazor WebAssembly

Add the references to the body tag of the index.html page after the _framework reference

Regardless of the Blazor project type you’re using, you’ll also need to add a reference to ChartJs.Blazor in _Imports.razor as detailed below.

@using ChartJs.Blazor

Adding Your First Chart

Now we’re ready to add a chart to one of the pages in our Blazor app. The first point of call is HTML. You can add a chart in a razor page with a <Chart> tag. This tag takes a parameter called Config. Let’s first create the tag before we look at creating the parameter to be passed through.

<Chart Config="_chartConfig"></Chart>

You’ve probably figured out based on the above, that we need to refer to an object called _chartConfig, but what kind of chart are we referring to?

Well, in this example, I’m going to create a pie chart. The type of object that _chartConfig will be depends on the type of chart. So in this example, I’ll need to use a PieConfig.

Place a private PieConfig at the top of the page’s code block.

private PieConfig _chartConfig;

Now we need to initialise this config object, which is where we override Blazor’s classic OnInitializedAsync()

protected override async Task OnInitializedAsync()
{
    _chartConfig = new PieConfig
    {
        Options = new PieOptions
        {
            Responsive = true, 
            Title = new OptionsTitle
            {
                Display = true,
                Text = "% Developers Using Chart.js in Blazor"
            }
        }
    };

}

As shown in the example above, we create several objects when initialising _chartConfig. We specify our options, stating that the chart should be responsive, (allowing it to appropriately resize based on the dimensions of the window) and we gave our chart a name, whilst specifying that the name should be displayed.

For this example, I’m creating a simple chart that shows the ratio of developers who use Chart.js in Blazor against those who do not.

Next up, labels and data.

Adding Labels and Data

Let’s add labels that can represent each data point. For this example, we have two data points that we will be adding shortly. ‘Using’ and ‘Not Using’

_chartConfig.Data.Labels.Add("Using");
_chartConfig.Data.Labels.Add("Not Using");

Now to add the data. To represent data, we add a dataset to the config object. In real-world scenarios, this would be data that has been obtained from another source, such as a database, but for this example we can hard-code some values. There are various types of dataset objects depending on the kind of chart you’re using, which take a generic type for the data to be represented. We’re using a pie chart which displays numerical values, so we’ll add a PieDataSet<int>

int usedPercentTotal = 60;
int notUsedPercentTotal = 40;
PieDataset<int> dataset = new PieDataset<int>(new[] { notUsedPercentTotal, usedPercentTotal })
{
    BackgroundColor = new[]
    {
        ColorUtil.ColorHexString(255, 205, 86),
        ColorUtil.ColorHexString(75, 192, 192)
    }
};

The code above creates a dataset using two integer values. We’ve also added a new array of background colours, using hex values to be shown for each respective total in the pie chart.

We can now add the above dataset to the config’s dataset collection.

_chartConfig.Data.Datasets.Add(dataset);

Here is our completed razor page code, followed by the rendered output

@using ChartJs.Blazor.PieChart
@using ChartJs.Blazor.Util
@using ChartJs.Blazor.Common

<Chart Config="_chartConfig"></Chart>

@code {

    private PieConfig _chartConfig;

    protected override async Task OnInitializedAsync()
    {
        _chartConfig = new PieConfig
        {
            Options = new PieOptions
            {
                Responsive = true,
                Title = new OptionsTitle
                {
                    Display = true,
                    Text = "% Developers Using Chart.js in Blazor"
                }
            }
        };

        _chartConfig.Data.Labels.Add("Using");
        _chartConfig.Data.Labels.Add("Not Using");

        int usedPercentTotal = 60;
        int notUsedPercentTotal = 40;
        PieDataset<int> dataset = new PieDataset<int>(new[] { notUsedPercentTotal, usedPercentTotal })
        {
            BackgroundColor = new[]
            {
                ColorUtil.ColorHexString(255, 205, 86),
                ColorUtil.ColorHexString(75, 192, 192)
            }
        };

        _chartConfig.Data.Datasets.Add(dataset);
    }

}

For more content like this, head over to my YouTube channel or check out more of my blog posts. If you want to discuss this or any other content further, feel free to contact me.

author image

About NIck

Leave a Reply

Your email address will not be published. Required fields are marked *

You Might Also Like...