Replies: 2 comments
|
That is expected because when condition is toggled off, children will be unmounted. But your approach to the problem is wrong. Chart js is expecting a canvas element to mount to, as long as you provided that element, you are good. Ref comes in two flavors, function form is the one you need: import { Chart } from 'chart.js/auto';
import { createSignal, Show } from 'solid-js';
const data = [
{ year: 2010, count: 10 },
{ year: 2011, count: 20 },
{ year: 2012, count: 15 },
{ year: 2013, count: 25 },
{ year: 2014, count: 22 },
{ year: 2015, count: 30 },
{ year: 2016, count: 28 },
];
const createChart = (ref: HTMLCanvasElement) => {
new Chart(ref, {
type: 'bar',
data: {
labels: data.map(row => row.year),
datasets: [
{
label: 'Acquisitions by year',
data: data.map(row => row.count)
}
]
}
});
}
function Test() {
const [show, setShow] = createSignal(false);
return (
<>
<button id="show-button" onClick={() => setShow((p) => !p)}>
{show() ? 'Hide' : 'Show'}
</button>
<Show when={show()}>
<canvas ref={(el) => createChart(el)} width="800" height="400" />
</Show>
</>
);
}
render(() => <Test />, document.body); |
0 replies
|
Thanks, @snnsnn, I didn't know you could call a function to assign the ref. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi, I'm trying to use the Show tag to show a chart (using Chart.js). There's a canvas element I've placed inside Show where I'm using ref={chartCanvas} attribute to assign a variable. However, when I go to initialize the chart in onMount(), the canvas element is undefined (was not assigned in ref={}). Since I need to initialize the chart with a valid context (from the canvas), I can't create it here. I'm guessing this is because the elements wrapped by Show tags don't exist (or aren't mounted) until the Show condition becomes true. I can work around it by not using Show and doing some manual set/remove 'hidden' attribute on a div or something, but is there a good way to handle this while still using Show?
Sample test code (if I comment out the Show tags, the chart renders):
All reactions