Configuring Chart.js for SvelteKit: A Comprehensive Tutorial

Configuring Chart.js for SvelteKit: A Comprehensive Tutorial

Using Chart.js with SvelteKit: A Step-by-Step Guide

sveltekit
chartjs

Chart.js is one of the best choices for visualizing data. In this blog post, I'll show you the optimized way to install and configure Chart.js in a SvelteKit project.

To integrate Chart.js, we need to complete a couple of steps:

  1. Write a reusable Chart.js render function.
  2. Define the HTML markup with a canvas element to serve as the placeholder for Chart.js.
  3. Define the data required for the chart.
  4. Import the data and render function, and use a Svelte action to pass the data to the render function.

Let's start executing all these steps one by one -

  1. Install chartJs
    terminal
    npm i -D chart.js
  2. Create a folder named 'Actions' in the 'lib' folder. Then, create a file named 'chartRender.js'.
    We will write a reusable action here called chartRender. It is an arrow function that accepts two parameters. When we use this action, the 'node' parameter will be automatically assigned to the HTML component.
    We will create the data for the Chart.js and pass it as the 'options' parameter.
    chartRender.js
    //importing chartjs from node_modules
    import { Chart } from 'chart.js/auto';
    //here we are exporting const variable, which is an arrow function,
    //and the arrow function takes one argument called node
    export const chartRender = (node, options) => {
     console.log('Action')
     console.log(node)
     console.log(options)
    
     new Chart (node, options)
    }
  3. Next, import the 'chartRender.js' file wherever necessary. In my case, I am importing it in my +page.svelte page.
    +page.svelte
    <script>
    //importing chartRender from Action file that exported a while ago
     import {chartRender} from '../Actions/chartRender'
    </script>
    <main>
    //this is just a simple canvas with action
       <canvas  use:chartRender>
       </canvas>
    </main>
  4. Now, if you check the console, you will see the console log. Our action is ready. Next, let's create a file to store all the data for Chart.js. Make sure to export that data so that we can use it in another file.In my case I created a file in lib > data > chartData.js
    chartData.js
    export const BarData = {
     type: 'bar',
     data: {
         labels: ['January','February', 'March', 'April', 'May'],
         datasets: [{
             label: 'Bar Dataset',
             data: [55,20,30,10,85],
             backgroundColor:[
                 'rgba(245, 40, 145, 0.8)'
             ]
         },],
     },
     options: {
         maintainAspectRatio: false,
     },
    }
    To achieve the desired tasks in the '+page.svelte' file, follow these steps: A. Import the data B. Set the data to the canvas options
    +page.svelte
    <script>
     import { chartRender } from './../../../lib/Actions/chartRender.js';
     import {BarData} from '../../../lib/Data/exp/chartData.js';
    </script>
    <main class="text-center">
     <div class="w-2/5 h-44 border m-auto">
         <canvas use:chartRender={BarData}></canvas>
     </div>
    </main>

Now, we can run npm run dev and check the result in the browser. At this point, Chart.js should be visible in the browser. At this point our integration is complete. If you need to update the data of Chart.js, you can do so by following the next step: update your 'chartRender.js' file.

Since chartRender.js serves as the main chart template, we should implement the update and destroy functions inside it. Keep in mind that the update function should be called when we update the Chart.js data, while the destroy function should be called when we hide the Chart.js.

chartRender.js
import Chart from '../../../node_modules/chart.js/auto/auto'
export const chartRender = (node, options) => {
    console.log("Chart Render is called: ")
    const _chart = new Chart (node, options)
    return {
        update(updatedoptions) {
            _chart.data = updatedoptions.data
            _chart.update()
        },
        destroy(){
            console.log("Destroy function is called:")
            _chart.destroy()
        }
    }
}