Work in Progress: How to add Chart.js to your flow

Here’s a quick guide and one way on how to add chart.js

We will need to do 3 key steps:

  • Create a chart container.

  • Create a Data Output (you can also do it with a computed field)

  • Trigger the Data Output on page load.

  1. Create a chart container, leave it empty and remember the key (in this case is going to be “chart_container”.)

  2. Add your chart.js code inside your Data Output. You can use this one as a template, but we suggest you read the Chart.js documentation for more customization herehttps://www.chartjs.org/docs/latest/

function output(userData, context) {
  setTimeout(() => {
    // Savvy setup for displaying the chart
    const chartEl = document.createElement("div");
    chartEl.innerHTML = '<canvas id="myChart"></canvas>';
    document.querySelector(".ComponentKey-chart_container").appendChild(chartEl);
    const scriptEl = document.createElement("script");
    scriptEl.src = "<https://cdn.jsdelivr.net/npm/chart.js>";
    scriptEl.onload = loadChart;
    document.body.appendChild(scriptEl);

		//Chart.js setup (read the docs!)
    const labels = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
    const data = {
      labels: labels,
      datasets: [
        {
          label: "# of Votes",
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1,
        },
      ],
    };
    const config = {
      type: "bar",
      data: data,
      options: {
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      },
    };
    function loadChart() {
      const myChart = new Chart(document.getElementById("myChart"), config);
    }
  }, 500);
}
  1. Once you created your container and created your data output with your chart.js code inside, you’ll need to trigger it on page load, in the page you need or before, not after.

  2. Select the page you want to execute, go to triggers, and select the data output you want to execute on page load

  3. Done! You will see your chart displayed inside your “chart_container” on your flow.

Last updated