Skip to content

Instantly share code, notes, and snippets.

@n2o
Last active January 4, 2022 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save n2o/459fcbb11a8040a4d82c40d3f1ed0eb9 to your computer and use it in GitHub Desktop.
Save n2o/459fcbb11a8040a4d82c40d3f1ed0eb9 to your computer and use it in GitHub Desktop.
Creating graphs with chart.js, ClojureScript, devcards and om.next

I have a huge amount of data in an Excel-Sheet and want to get some statistics of it. Since I am only using LibreOffice, which is not very comfortable, and I am really loving web-techniques to build UIs / visualizations, I decided to use devcards and ClojureScript with React.js to build some Charts.

This is inspired by this gist, but I want to use it with om.next and devcards, which is why I am writing this gist.

The react.js component in om.next syntax looks like this:

(defui BarChart
  Object
  (componentDidMount
   [this]
   (let [chart (dom/getElement "myChart")
         chart-data {:type "bar"
                     :data {:labels ["2013" "2014" "2015" "2016" "2017"]
                            :datasets [{:data [5 10 15 20 25]
                                        :label "Rev in MM"
                                        :backgroundColor "#90EE90"}
                                       {:data [3 6 9 12 15]
                                        :label "Cost in MM"
                                        :backgroundColor "#F08080"}]}}]
     (js/Chart. chart (clj->js chart-data))))
  (render [this]
          (html [:canvas#myChart {:width 400 :height 400}])))

It creates a DOM-element and after this element has mounted, it calls the chart.js function to build the graph.

To make the state accessible, I define a reconciler, which is currently empty and will be sufficient for this gist. Only for the sake of completeness.

(defonce reconciler
  (om/reconciler {:state {} :parser nil}))

Then create the devcard:

(defcard bar-chart
  (dom-node
   (fn [_ node] (om/add-root! reconciler BarChart node))))

Don't forget to include chart.js to your HTML-document.


chart.js example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment