1

Did anyone have an idea or know how to implement chart.js in qwik without having to convert it with react and @qwikify ?

I need to implement a component that has a donut chart.js built in it, unfortunately i can not figure out how to make it work, mainly because i haven't find an alternative to document.getElementByID for the ctx value.

FG99
  • 11
  • 1

1 Answers1

1

is possible to get the context using useSignal$ with useVisibleTask$. Just and example...

import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import { Chart, registerables } from 'chart.js';


export default component$(() => {
  const myChart  = useSignal<HTMLCanvasElement>();

  useVisibleTask$(() => {
    if (myChart?.value) {
      Chart.register(...registerables);
      new Chart(myChart.value, {
        type: 'bar',
        data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    }
  });

  return (
    <div>
      <canvas ref={myChart} id="myChart"></canvas>
    </div>
  );
});
Rafael
  • 601
  • 7
  • 10