How to use chart.js with lit-html

150 views Asked by At

I am using render() to create and render using lit-html

import { html, render } from 'lit-html';
const templateItems = [];

const getChartInfo = (locationToRender) => {
  templateItems.push(html`
    <span>Welcome to charts </span>
    `);
  render(templateItems, locationToRender);
};

export default getChartInfo;

How do I use chart.js(https://www.chartjs.org/docs/latest/getting-started/usage.html) in it?

Looking at doc, firstupdated() (https://lit.dev/docs/components/lifecycle/#firstupdated) might be the right hook? If so, how do I use it?

If no, how do I do it?

1

There are 1 answers

0
Christian On

When using lit-element, you need to render a canvas, as any other element. E.g.

render(): TemplateResult {
    return html`
      <div class="chart-wrapper">
        <canvas class="chart" ${ref(this.chartjsElementRef)}></canvas>
      </div>
    `;
  }

During the lifecycle e.g. on firstUpdated:

 protected firstUpdated(_changedProperties: PropertyValues) {
    super.firstUpdated(_changedProperties);
    this.chart = new Chart(
      this.chartjsElementRef.value!,
      <chartconfig>
    );
}