Search code examples
javascriptchartkickmithril.js

Converting JS to Mithril (using Chartkick)


I'm trying to add Chartkick to an application that uses Mithril.

How would I convert the code below to be used with Mithril?

<h1>Line Chart</h1>
<div id="line" style="height: 300px;"></div>
<script>
  new Chartkick.LineChart("chart-1", "/stocks")
</script>

The Mithril page:

import m from 'mithril';
import _ from 'underscore';
import h from '../h';
import projectShareBox from './project-share-box';
import facebookButton from './facebook-button';
import addressTag from './address-tag';
import categoryTag from './category-tag';

const projectHighlight = {
    controller() {
        return {
            displayShareBox: h.toggleProp(false, true)
        };
    },
    view(ctrl, args) {
        const project = args.project;

        return m('#project-highlight', [
            m('.w-row.u-marginbottom-60', [
                m('.w-col.w-col-12.u-text-center', {
                    style: {
                        'min-height': '300px'
                    }
                }
            ]),

Solution

  • You'll want to use the oncreate vnode lifecycle hook.

    Here's an example:

    m.mount(document.body, {
        view() {
            return m(".chart", {
                oncreate(vnode) {
                    vnode.state.chart = new Chartkick.LineChart(
                        vnode.dom,
                        {
                            one : 1,
                            two : 2,
                            three : 3
                        }
                    );
                }
            });
        }
    });
    

    Working example of that code: https://jsbin.com/gogucuv/2/edit?html,js,output