r/HyperApp • • May 30 '18

Help with Chart.js example?

Hi,

can anyone point me how/if it would be easy to user Hyperapp with Chart.js? I always have trouble with vdom frameworks because those big charting libraries are (still) always made in the "real dom/jquery is the way" world.

http://www.chartjs.org/docs/latest/

Some hyperapp Github issues mention examples on the wiki, but the wiki seems gone now.

TIA

2 Upvotes

2 comments sorted by

View all comments

Show parent comment

2

u/[deleted] May 30 '18

Thank you - that worked fine. Will try to understand it better now.

Here's the working code just in case:

import { h, app } from "hyperapp"
import Chart from 'chart.js';

/***
 * Chart.JS stuff
 */

function MyChart(props) {
    return h('canvas', {
        oncreate: (element) => {
            let ctx = element.getContext('2d');
            let data = props.myData // or whatever
            let myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                    datasets: [{
                        label: '# of Votes',
                        data: data,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255,99,132,1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }
        //   onupdate: ...,
        //     onremove: ...,
        //     ondestroy: ...,
    })
}

/***
 * Hyperapp stuff
 */

const state = { title: "Hi." }
const actions = {}

const view = (state, actions) =>
    h('div', {}, [
        MyChart({ myData: [50, 50, 30, 12, 21, 30] })
    ])


app(state, actions, view, document.body)

The template what created with: https://github.com/hyperapp/cra-hyperapp instructions, changing only index.js.