React.js and Google Charts

So today I was integrating Google Charts into a frontend app created with react.js. As it always is when you want to integrate a 3rd party solution with react components you need a little bit of manual work. But fortunatelly react gives us an easy way to combine those two things together.

var GoogleLineChart = React . createClass ({ render : function (){ return React . DOM . div ({ id : this . props . graphName , style : { height : " 500px " }}); }, componentDidMount : function (){ this . drawCharts (); }, componentDidUpdate : function (){ this . drawCharts (); }, drawCharts : function (){ var data = google . visualization . arrayToDataTable ( this . props . data ); var options = { title : ' ABC ' , }; var chart = new google . visualization . LineChart ( document . getElementById ( this . props . graphName ) ); chart . draw ( data , options ); } });

As you can see all you need to do is to hook code responsibile for drawing charts (which comes from another library and is not done in react-way) into the proper lifecycle methods of the react componenet. In our case it is:

One more thing. Make sure you start rendering components only after the javascript for google charts have been fully loaded.

InsightApp . prototype . start = function () { that = this ; var options = { dataType : " script " , cache : true , url : " https://www.google.com/jsapi " , }; jQuery . ajax ( options ). done ( function (){ google . load ( " visualization " , " 1 " , { packages :[ " corechart " ], callback : function () { that . startRenderingComponents (); } }); }); };

You can see the effect here:

These are the things that I learnt today while integrating our code with Google Charts. In my next blogpost I would like to share how we dealt with a similar problem when using Twitter Bloodhound library for autocomplete.