<script lang="ts">
import { onMount } from 'svelte';
import { Chart } from 'frappe-charts';
let chartElem;
const chartData = {
labels: ["12am-3am", "3am-6pm", "6am-9am", "9am-12am",
"12pm-3pm", "3pm-6pm", "6pm-9pm", "9am-12am"
],
datasets: [
{
name: "Some Data", type: "bar",
values: [25, 40, 30, 35, 8, 52, 17, -4]
},
{
name: "Another Set", type: "line",
values: [25, 50, -10, 15, 18, 32, 27, 14]
}
]
};
onMount(() => {
console.log(chartElem); // always undefined... why??
new Chart({
parent: chartElem,
title: "My Awesome Chart",
data: chartData,
type: 'axis-mixed', // or 'bar', 'line', 'scatter', 'pie', 'percentage'
height: 250,
colors: ['#7cd6fd', '#743ee2']
});
});
<div bind:this={chartElem}>loading chart...</div>
I was trying to plot a chart in my Svelte component and above is my current code. According to the Svelte doc, bind:this
is the way to refer to the dom node chartElem
so that in the component code I can plot a chart onto that div
.
But somehow I keep getting undefined
with my chartElem
variable. Where did I do wrong? Or Perhaps I'd need to go for a different chart library other than Frappe Chart?
Looks like the way I instantiated the Frappe Chart object might be wrong. I made a few tweaks to the original code.
This worked for me.
Also, worth registering the
onDestroy
lifecycle method so that the chart object can be cleaned properly.