Blazor component for Chart.js

After a lot of work, I finally complete the first implementation of my Blazor component for ChartJS for Blazor WebAssembly and Blazor Server. This component helps you to create beautiful graphs with the famous JavaScript library for chart called ChartJS.

Following a couple of experiments with ChartJS

I decided to start to write a faced for Blazor. There is a project on GitHub, but it is old and not maintained any more.

The demo site is live here. The source code of the component and the demo is available on GitHub.

My component

So, I restarted from scratch using NET6 and the latest version of ChartJS at the present the version 3.7.1.

With the current implementation, you can create the following charts:

  • Area
  • Bar
  • Bubble
  • Doughnut
  • Pie
  • Line
  • Polar Area
  • Radar
  • Scatter

To use the Blazor component for ChartJS in your Blazor WebAssembly or Blazor Server project, the first thing is to add the ChartJS library and the JavaScript for the component in your Index.html. Before closing the tag body, add the following lines

<script src="_content/PSC.Blazor.Components.Chartjs/lib/Chart.js/chart.js"></script>
<script src="_content/PSC.Blazor.Components.Chartjs/Chart.js"></script>

I added the ChartJS library in the component, so, if you use the version from the component, you know the generation of the charts is correct and working. Maybe with the next versions of the library, I have to change the model.

Then, you have to add in your _Imports.razor the following namespaces

@using PSC.Blazor.Components.Chartjs
@using PSC.Blazor.Components.Chartjs.Enums
@using PSC.Blazor.Components.Chartjs.Models
@using PSC.Blazor.Components.Chartjs.Models.Common
@using PSC.Blazor.Components.Chartjs.Models.Bar
@using PSC.Blazor.Components.Chartjs.Models.Bubble
@using PSC.Blazor.Components.Chartjs.Models.Doughnut
@using PSC.Blazor.Components.Chartjs.Models.Line
@using PSC.Blazor.Components.Chartjs.Models.Pie
@using PSC.Blazor.Components.Chartjs.Models.Polar
@using PSC.Blazor.Components.Chartjs.Models.Radar
@using PSC.Blazor.Components.Chartjs.Models.Scatter

So, how you can see, there is a namespace for each type of charts plus the generics (Enums, Models and the base). This allows you to use the component across your application.

Create the first bar graph

Now, in your Blazor project, create a new Razor Component and add this line

<Chart Config="_config1" @ref="_chart1"></Chart>

Chart is the common name for the Blazor component for ChartJS. Only one component for all the charts. Now, in the code add this code

@code {
    private BarChartConfig _config1;
    private Chart _chart1;

    protected override async Task OnInitializedAsync()
    {
        _config1 = new BarChartConfig()
        {
            Options = new Options()
            {
                Plugins = new Plugins()
                {
                    Legend = new Legend()
                    {
                        Align = LegendAlign.Center,
                        Display = false,
                        Position = LegendPosition.Right
                    }
                },
                Scales = new Scales()
                {
                    X = new XAxes()
                    {
                        Stacked = true,
                        Ticks = new Ticks()
                        {
                            MaxRotation = 0,
                            MinRotation = 0
                        }
                    },
                    Y = new YAxes()
                    {
                        Stacked = true
                    }
                }
            }
        };

        _config1.Data.Labels = BarDataExamples.SimpleBarText;
        _config1.Data.Datasets.Add(new BarDataset()
        {
            Label = "Value",
            Data = BarDataExamples.SimpleBar.Select(l => l.Value).ToList(),
            BackgroundColor = Colors.Palette1,
            BorderColor = Colors.PaletteBorder1,
            BorderWidth = 1
        });
    }
}

When the page is initialized in the OnInitializedAsync I create the configuration for the chart. For the options, please refer to the ChartJs documentation.

This is the result of this code.

Bar chart with the Blazor component for ChartJS
Bar chart with the Blazor component for ChartJS

Use the right Chart configuration

Each chart has its ChartConfig to use.

ChartChart config
BarBarChartConfig
BubbleBubbleChartConfig
DoughnutDoughnutChartConfig
LineLineChartConfig
PiePieChartConfig
PolarPolarChartConfig
RadarRadarChartConfig
ScatterScatterChartConfig

For more information about the chart configuration, look at the demo website (where there is for each graph the code) or the source code on GitHub.

How to fix the size of the graph with ChartJS

So, this is a very common problem with ChartJs. This is an example of the issue. Although, you add the style to the chart, the chart removes all your settings and the result is not what you expect.

Issue with the size of the graph with ChartJS
Issue with the size of the graph with ChartJS

If you don’t use my component, you have to wrap the canvas in a div and add the style like that

<div id="wrapper" style="position: relative; height: 50vh">
    <canvas id="chart"></canvas>
</div>

Then, in the chart options, you have to set

new Chart(ctx, {
    // ... other config ...
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});

If your wrapper doesn’t have a relative size, you should be able to dynamically change the height of the chart by changing the height of the wrapper:

document.getElementById("wrapper").style.height = '128px';

How to fix the size of the graph with the Blazor component for ChartJS

If you use my component, it is easier. In the ChartConfig you have to add those lines:

_config1 = new LineChartConfig()
{
    Options = new Options()
    {
            Responsive = true,
            MaintainAspectRatio = false
    }
};

Adding Responsive and MaintainAspectRatio to the chart configuration, the chart will be displayed with the size you want. So, the result is like in the following screenshot.

The chart size is fixed with Blazor component for ChartJS
The chart size is fixed with Blazor component for ChartJS

Wrap up

In conclusion, this is my new Blazor component for ChartJS that you can use in your projects. Few important links:

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

This site uses Akismet to reduce spam. Learn how your comment data is processed.