ChartJs.Blazor

by mariusmuntean

mariusmuntean / ChartJs.Blazor

Brings Chart.js charts to Blazor

330 Stars 68 Forks Last release: 7 months ago (v1.1.0) MIT License 438 Commits 15 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

Chart.js interop with Blazor

License: MIT GitHub issues GitHub forks GitHub stars

Join the chat at https://gitter.im/ChartJs-Blazor/community

NuGet Downloads

Netlify Status

Introduction

This is a Blazor library that wraps Chart.js. You can use the library in both client- and server-side projects. See the Getting Started, browse the samples or reach out on Twitter if you need help.

Don't know what Blazor is? Read here.

Getting started

Prerequisites

You need an IDE that supports Blazor and .Net Core SDK 3.x+

  1. Visual Studio 2019 (Community Edition is fine) or VisualStudio for Mac or Jetbrains Rider
  2. .NET Core 3.0 or newer

Installation

There's a NuGet package available: ChartJs.Blazor

In case you prefer the command line:

dotnet add package ChartJs.Blazor

Usage

Assets

Before you can start creating a chart, you have to add some static assets to your project. These come bundled with ChartJs.Blazor, so you only need to add a few lines to your

Index.html
/
_Host.cshtml
.

In your

_Host.cshtml
(server-side) or in your
index.html
(client-side) add the following lines to the
body
tag after the
_framework
reference








Imports

Now add a reference to

ChartJs.Blazor
in your
_Imports.razor
csharp
@using ChartJs.Blazor;

Chart

Now you can create a .razor file where you display one of the charts. Let's show a pie chart with 4 slices πŸ•.

Make your page known to the router by adding a

@page
statement
csharp
@page "/MyPieChart"

Then add a few

@using
statements
csharp
@using ChartJs.Blazor.Charts
@using ChartJs.Blazor.ChartJS.PieChart
@using ChartJs.Blazor.ChartJS.Common.Properties
@using ChartJs.Blazor.Util

Below the

@using
statements add a
ChartJsPieChart
component
html

The last step is to make the
ChartJsPieChart
from above, reachable from your code to configure it and to give it some data to display. In the
@code
section of your .razor file create matching variables to reference the chart and its configuration. Finally, give your chart a title and some data. The finished code should look like this:
private PieConfig _config;
private ChartJsPieChart _pieChartJs;

protected override void OnInitialized() { _config = new PieConfig { Options = new PieOptions { Title = new OptionsTitle { Display = true, Text = "Sample chart from Blazor" }, Responsive = true, Animation = new ArcAnimation { AnimateRotate = true, AnimateScale = true } } };

_config.Data.Labels.AddRange(new[] { "A", "B", "C", "D" });

var pieSet = new PieDataset
{
    BackgroundColor = new[] { ColorUtil.RandomColorString(), ColorUtil.RandomColorString(), ColorUtil.RandomColorString(), ColorUtil.RandomColorString() },
    BorderWidth = 0,
    HoverBackgroundColor = ColorUtil.RandomColorString(),
    HoverBorderColor = ColorUtil.RandomColorString(),
    HoverBorderWidth = 1,
    BorderColor = "#ffffff",
};

pieSet.Data.AddRange(new double[] { 4, 5, 6, 7 });
_config.Data.Datasets.Add(pieSet);

}

Breakdown

First, in your

Index.html
/
_Host.cshtml
you've added references to static assets from
ChartJs.Blazor
. During build time, library assets get packaged under _content/LibraryName.

Then, you've imported

ChartJs.Blazor
in your
_Imports.razor
. The Blazor Team mentioned that this shouldn't be necessary in the future.

In your .razor file you added the

ChartJsPieChart
component and gave it some width and height. You specified that the component should use the variable
_config
as the chart's configuration object. You also told Blazor that you want a direct reference to the chart and that the reference should be saved in your
_pieChartJs
variable.

When your page's

OnInitialized()
method is executed you're setting the chart's configuration and dataset to be displayed.

Known Limitations

Library

  • Client-side Blazor projects are currently affected by a bug in

    JSON.NET
    tracked by this issue.

    There are two known workarounds:

    • Prefered Option - add a file named Linker.xml to the root of your client-side project to instruct the Mono linker to keep a certain constructor that
      JSON.NET
      invokes via reflection. Make sure to select
      BlazorLinkerDescription
      as the build action of the
      Linker.xml
      file. In case that your IDE doesn't offer that option, simply edit the
      .csproj
      file and add this to it:
      xml
          
              
          
      
      The content of the
      Linker.xml
      should be similar to this (adjust to your project's entry point assembly):
      xml
          
          
          
              
                  
                  
              
              
                  
                  
              
              
              
              
              
                  
                  
                  
              
          
      
    • Alternative Option - include the following line in the parent component:

      private ReferenceConverter ReferenceConverter = new ReferenceConverter(typeof(PROBLEMATIC_COMPONENT));
      

      where

      PROBLEMATIC_COMPONENT
      is a placeholder for the chart-component you're using inside this component (e.g.
      ChartJsBarChart
      ,
      ChartJsPieChart
      ,
      ChartJsLineChart
      , ..).

Samples

  • When publishing the client-side Blazor sample, the generated dist folder is missing _content\ChartJs.Blazor. This seems to be a known bug in the current version of client-side Blazor. To work around this bug you need to go to the publish folder and locate the wwwroot folder. There you should find the missing _content folder. Copy the _content folder to the dist folder. The final dist folder should look like this
    shell
    β”‚   index.html
    β”‚
    β”œβ”€β”€β”€css
    β”‚   β”‚   site.css
    β”‚   β”‚
    β”‚   β”œβ”€β”€β”€bootstrap
    β”‚   β”‚       bootstrap.min.css
    β”‚   β”‚       bootstrap.min.css.map
    β”‚   β”‚
    β”‚   └───open-iconic
    β”‚       β”‚   FONT-LICENSE
    β”‚       β”‚   ... truncated for brevity
    β”‚
    β”œβ”€β”€β”€_content
    β”‚   └───ChartJs.Blazor
    β”‚           Chart.min.js
    β”‚           ChartJSBlazor.css
    β”‚           ChartJsBlazorInterop.js
    β”‚           moment-with-locales.min.js
    β”‚
    └───_framework
    β”‚   blazor.boot.json
    β”‚   blazor.server.js
    β”‚   blazor.webassembly.js
    β”‚
    β”œβ”€β”€β”€wasm
    β”‚       mono.js
    β”‚       mono.wasm
    β”‚
    └───_bin
            ChartJs.Blazor.dll
            ChartJs.Blazor.pdb
            ... truncated for brevity
            System.Xml.Linq.dll
    

Dig deeper

For detailed instructions read the Chart.js documentation to understand how each chart works.

A word on the samples

The current samples are flawed in many ways. If you would like to help improving them, please see this issue.

The samples folder contains three projects, one for a client-side Blazor app, another one for a server-side Blazor app and a shared project. The shared project is not really necessary but that is how we chose to avoid code duplication.

Unlike the documentation, the samples should always be up to date with the current development on master. That means, that the code you see in the samples folder on master might not actually compile on the current nuget version. To browse the samples for the latest nuget version, see the samples on the releases branch.

To make it easier for you to see what ChartJs.Blazor can do, we host the client-side samples with Netlify on www.iheartblazor.com (and a few other domains 😁). However, the demo page might lag behind a bit too so if you want to be sure, compile the samples on the releases branch.

If you go to the demo page, you should see something like this: Charts

Contributors

This projects slowly develops a community which started to give back.

Special thanks to:

  • Joelius300 for keeping the project alive, developing it further and finally giving me the needed motivation to revive it.

Many thanks to:

We're very grateful for your contributions!

Contributing

We really like people helping us with the project. Nevertheless, take your time to read our contributing guidelines here.

Also keep in mind that this library is just a bridge from Blazor (C#) to Chart.js (JavaScript) so if you have a question on how to achieve something or experience unexpected behaviour, research how to do/fix it with JavaScript and only when you know how to get the correct behaviour in JavaScript open an issue here with all that information. It will greatly help us to give feedback and prevents us from wasting our limited time on issues that aren't really connected to this library. Thank you!

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.