Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AnyChart the HTML version be used with React?

I would like to use AnyChart library with my current React, Redux stack. Is there a way to wrap AnyCharts in something like FauxDom. Would be nice if you can provide me with a sample code snippet or direction to a library that does that.

like image 684
Algimantas Krasauskas Avatar asked Jan 05 '23 13:01

Algimantas Krasauskas


1 Answers

As for the client side React rendering, it is surely possible to use AnyChart wrapped in a React component.

You could write a wrapping AnyChart component accepting the data array and title as props in this way (example of a pie chart wrapper):

import React, { Component } from 'react';

class AnyChart extends Component {

  constructor(props) {
    super(props);
  }

  // Important, otherwise the re-render
  // will destroy your chart
  shouldComponentUpdate() {
    return false;
  }

  componentDidMount() {

    // Get data from the props
    let data = this.props.data;
    let title = this.props.title;

    // Let's draw the chart
    anychart.onDocumentReady(function() {
      let chart = anychart.pie(data);
      chart.container('chart');
      chart.title(title);
      chart.draw();
    });
  }

  render() {
    return (
      <div id="chart" style={{height: '400px'}}/>
    );
  }
}

export default AnyChart;

You can then use this component from another react component. For example, from a functional component:

import React from 'react';
import AnyChart from './AnyChart';
const AnyChartTest = (props) => {

  const data = [
    ['React', 5200],
    ['ES6', 2820],
    ['Redux', 2650],
    ['Redux Ducks', 670]
  ];

  return (
    <div>
      <h1>AnyChart Test</h1>
      <AnyChart data={data} title="Technology Adoption" />
    </div>
  );
};

export default AnyChartTest;

This works well if you don't need to have the chart dynamically updated with new data from the props. If that is the case you should add a ComponentWillReceiveProps handler in the AnyChart wrapper component, where you should pass new data from the props to the chart and force a redraw.

Stephen Grider made a very good video on third party components integration: https://www.youtube.com/watch?v=GWVjMHDKSfU

I hope I helped you, at least for client-side rendering.

Matteo Frana

like image 55
Matteo Frana Avatar answered Jan 18 '23 01:01

Matteo Frana