Search code examples
javascriptjqueryreactjsflot

How to integrate FlotJs into ReactJs


I am trying to integrate Flot charts into React but I get $.plot is not a function error, I have the following code

Script tags Index.html

<script src="dist/libs/js/jquery.min.js"></script>
<script src="dist/libs/js/jquery.flot.js"></script>
<script src="dist/libs/js/jquery.flot.stack.js"></script>
<script src="dist/libs/js/jquery.flot.symbol.js"></script>

My React component

class OfferGraph extends React.Component {
  constructor(){
    super();
    this.state ={
      isLogged:false
    }

    //Test Code 
    let node = $('#trackInsightGraph');
    $.plot(node, [{
      data: data['searchAverage'],
      points: {show: false}
    }, {
      data: data['offer'],
      points: {show: false}
    }, {
      data: data['similar'],
      points: {show: false}
    }, {
      data: data['c01'],
      lines: {show: true}
    }], options);
  }

  render(){
    return <div id="trackInsightGraph">
    </div>
  }

}
export default OfferGraph;

I can't use another Chart library as most the functionality is written for Flot Please help, if some body can point out an example how these(Flot) jQuery plugins can be integrated into React


Solution

  • The problem with your code -- both the given and the unstated but assumed -- is that the constructor is going to be called first, before the chart container div is created in the render() function. And the constructor needs that container div. At least that's what I'm guessing based on the incomplete code given.

    I created a jsfiddle that shows how I would approach the issue. I'm using React.createClass() to create the component. Inside that, the renderChart() function is the actual drawing code and it uses a ref for the container that is created in the render() function.

    Both the data for the chart and the options are passed in through the call to ReactDOM.render() at the bottom of the code. That call creates the container (placing it in another container) and the two props are passed in at that time.

    (Note: I decided to not use JSX for this example. I leave the changes as an exercise for the reader.)