Tutorials

Creating Reusable React Components to Deploy Multiple Charts

ReactJS is a front-end library written in JavaScript that allows developers to create dynamic and responsive user interfaces. It allows you to divide your UI into reusable pieces that are functionally independent of one another. These are referred to as reusable components. Reusable components allow for faster development because the next time a developer needs to create a similar UI, they can reuse one of the previously created components, resulting in less code being written. Reusable components also aid in the maintenance of design consistency. In this post, you’ll learn how to create reusable react components to deploy multiple charts and  If you’re looking for a React Chart Tool, we suggest using fusioncharts for creating multiple charts with ReactJs.

Popularity with Developers

ReactJS topped the charts in a developer poll conducted by StackOverflow in 2017 to study library popularity among developers. Some of the reasons why ReactJS is so popular among developers include:
  • ReactJS is based on JavaScript and, on its own, ReactJS has a limited API and few functions. This is why a developer’s familiarity with JavaScript will help them ace ReactJS in not more than a few hours.
  • ReactJS gained immense popularity after Angular 2 deprecated backward compatibility. React’s performance benefits made it the best replacement for Angular 2.
  • With the speed of JavaScript and no dependence on a domain-specific language, React revolutionizes the programming of user interfaces.

Benefits of ReactJS

In addition to the reasons for its popularity among developers, ReactJS also offers the following advantages:
  • ReactJS gives developers the ability to build reusable components. This reusability is perhaps one of the most significant advantages that ReactJS has to offer since it also translates to saving time along with maintaining design consistency.
  • The components are isolated from each other. Change in one, therefore, does not affect the others unless it is allowed. This makes managing updates easy.
  • Downward data binding also ensures that changes in the structure of child components don’t affect the parents. This, in turn, provides code stability.
  • It is easier for search engines to index web pages built using React.

Integrating FusionCharts with ReactJS

About the React-FusionCharts Component

FusionCharts Suite XT comes with an extensive range of charts, widgets, and gauges to plot static and real-time data. The JavaScript-based charting library also has several basic and advanced configuration options helpful in creating the charts. The React-FusionCharts component lets you add interactive JavaScript charts to your web and mobile applications using a single reusable React component.

Downloading the Required Components

Before we start with how you can create charts using the React-FusionCharts component, you need to: Download FusionCharts Suite XT. The library is downloaded as a zip package. To install it, unzip and copy the downloaded files in your project folder. Download React-FusionCharts component. This is also downloaded as a zip package. Unzip this and copy the downloaded files into your project folder.

Integrating the FusionCharts Extension with ReactJS

To include the FusionCharts library and the React-FusionCharts component in your project, copy the following code and paste it in your JS file:
<script type="text/javascript" src="https://unpkg.com/react@0.13.3/dist/JSXTransformer.js"></script>
<script type="text/javascript" src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="https://unpkg.com/react-fusioncharts/dist/react-fusioncharts.js"></script>

Creating the Chart Instance

For this tutorial’s sample, we will create a column 2D chart. This chart will plot the top global oil reserves for the previous year.

Configuring the Chart and Creating the Data Source

To set the chart configuration and create the data source for the sample chart, copy the following code and paste it into your JS file:
{
        "chart": {
          "caption": "Top Global Oil Reserves",
          "subCaption": "[2015-16]",
          "xAxisName": "MMbbl= One Million barrels",
          "yAxisName": "Reserves (MMbbl)",
       // extra attributes 
          "numberSuffix": "K",
          "showValues": "0",
          "showLabels": "0",
          "showHoverEffect": "1",
          "use3DLighting": "0",
          "showaxislines": "1",
          "theme": "hulk-light"
 
     },
        "data": [{
          "label": "Venezuela",
          "value": "290"
     }, {
          "label": "Saudi",
          "value": "260"
     }, {
          "label": "Canada",
          "value": "180"
     }, {
          "label": "Iran",
          "value": "140"
     }, {
          "label": "Russia",
          "value": "115"
     }, {
          "label": "UAE",
          "value": "100"
     }, {
          "label": "US",
       "value": "30"
     }, {
          "label": "China",
          "value": "30"
     }]
   }

Creating the Reusable React Component

We’ll now create a component that will contain the basic chart configuration like the chart width and height, the data format, and the data source. In the subsequent sections, where we change a part of the chart’s configuration, we’ll reuse this component to retain the basic configuration of the chart. To create the chart component, copy the following code and paste it in your JS file:
var chartConfigs = {
     type: 'column2d',
        renderAt: 'chart-container',
     width: '550',
        height: '350',
        dataFormat: 'json',
        dataSource: myDataSource
   }
The chartConfigs component contains the chart’s basic configuration.

Changing the Chart Type

To change the chart type at runtime, copy the following code and paste it in your JS file:
const element = ( <div>
     Change Chart Type:
     <br /><label>
        <input name = 'chart-type'
     id = 'columntype'
     type = 'radio'
     value = 'column2d'/> Column </label> <label >
        <input name = 'chart-type'
     id = 'linetype'
     type = 'radio'
     value = 'line'/> Line </label>
 
        <label>
        <input name = 'chart-type'
     id = 'bartype'
     type = 'radio'
     value = 'bar2d'/> Bar </label> <label>
        <input name = 'chart-type'
     id = 'ptype'
     type = 'radio'
     value = 'pie2d'/> Pie </label> </div> );
 
        ReactDOM.render( < ReactFC {...chartConfigs
       }
          />,
          document.getElementById("top")
     );
     var refreshChart = function(){
        chartConfigs.type = "column2d";
        chartConfigs.dataSource.chart.caption = "Top Global Oil Reserves";
        chartConfigs.dataSource.chart.subCaption = "[2015-16]";
     delete chartConfigs.dataSource.chart.paletteColors;
        chartConfigs.dataSource.chart.showLabels = "0";
       chartConfigs.dataSource=myDataSource; ReactDOM.unmountComponentAtNode(document.getElementById('top'));
            ReactDOM.render( < ReactFC {...chartConfigs
              }
              />,
              document.getElementById("top")
         );
     };
        document.getElementById("nn").addEventListener("click", function() {
          refreshChart();
          console.log(this.getAttribute('id'));
          ReactDOM.render(element, document.getElementById("controllers"));
       var radio = document.getElementsByTagName('input');
          console.log(radio);
       for (i = 0; i < radio.length; i++) {
            radElem = radio[i];
         if (radElem.type === 'radio') {
              radElem.addEventListener("click", function() {
                console.log("fdf");
                var id = this.getAttribute('id');
                console.log(id);
                console.log(chartConfigs.type);
                switch (id) {
                  case "linetype":
                    val = this.getAttribute('value');
 
                    chartConfigs.type = val;
 
                    ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                    ReactDOM.render( < ReactFC {...chartConfigs
                      }
                      />,
                      document.getElementById("top")
                    );
                    break;
                  case "columntype":
                    val = this.getAttribute('value');
                    chartConfigs.type = val;
 
                    ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                    ReactDOM.render( < ReactFC {...chartConfigs
                      }
                      />,
                      document.getElementById("top")
                    );
                    break;
                  case "ptype":
                    val = this.getAttribute('value');
                    console.log(chartConfigs.type);
                 chartConfigs.type = val;
                    var t = Object.assign({}, chartConfigs);
                    ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                    ReactDOM.render( < ReactFC {...t
                      }
                      />,
                      document.getElementById("top")
                    );
                    break;
 
                  case "bartype":
                    val = this.getAttribute('value');
                    chartConfigs.type = val;
                    ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                    ReactDOM.render( < ReactFC {...chartConfigs
                      }
                      />,
                      document.getElementById("top")
                    );
                    break;
                }
              });
         }
       }
     });
This will render four radio buttons below the chart, allowing you to choose from the column, line, bar, and pie chart types. In the above code, the ReactDOM.render() method calls the chartConfigs  reusable react component to re-render the chart. This saves the developer from rewriting the chart’s basic configuration and focusing only on the updates in the configuration.

Changing the Chart Attributes

To update chart attributes at runtime, copy the following code and paste it in your JS file:
const secondElement = ( <div>
          Change Attribute: <br />
          <label>
          <input name = 'attr-type'
       id = 'Captiontype'
       type = 'radio'
          value = 'caption'/> Caption </label> <label>
          <input name = 'attr-type'
       id = 'sCaptiontype'
       type = 'radio'
          value = 'subCaption'/> Sub - Caption </label>
 
       <label>
          <input name = 'attr-type'
       id = 'pltype'
       type = 'radio'
          value = 'paletteColors'/> Palette Colors </label> <label>
          <input name = 'attr-type'
       id = 'labeltype'
       type = 'radio'
       value = 'showLabels'/> Show Labels </label> </div> );
 
          document.getElementById("kk").addEventListener("click", function() {
            refreshChart();
            console.log(this.getAttribute('id'));
            ReactDOM.render(secondElement, document.getElementById("controllers"));
            var radio = document.getElementsByTagName('input');
            console.log(radio);
            for (i = 0; i < radio.length; i++) {
              radElem = radio[i];
              if (radElem.type === 'radio') {
                radElem.addEventListener("click", function() {
                  console.log("fdf");
                  var id = this.getAttribute('id');
                  console.log(id);
                  console.log(chartConfigs.type);
               switch (id) {
                    case "Captiontype":
                      chartConfigs.dataSource.chart.caption = "Country-wise Oil Reserves";
                      chartConfigs.dataSource.chart.subCaption = "[2015-16]";
                      delete chartConfigs.dataSource.chart.paletteColors;
                      chartConfigs.dataSource.chart.showLabels = "0";
                      ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                      ReactDOM.render( < ReactFC {...chartConfigs
                     }
                     />,
                        document.getElementById("top")
                      );
                      break;
                    case "sCaptiontype":
                      chartConfigs.dataSource.chart.caption = "Top Global Oil Reserves";
                      chartConfigs.dataSource.chart.subCaption = "From Year 2015 to 2016";
                      delete chartConfigs.dataSource.chart.paletteColors;
                      chartConfigs.dataSource.chart.showLabels = "0";
 
                      ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                      ReactDOM.render( < ReactFC {...chartConfigs
                     }
                     />,
                     document.getElementById("top")
                      );
                      break;
                    case "pltype":
                      chartConfigs.dataSource.chart.caption = "Top Global Oil Reserves";
                      chartConfigs.dataSource.chart.subCaption = "[2015-16]";
                      chartConfigs.dataSource.chart.paletteColors = "#21EFE6,#E9EF21,#FAA609,#D3A7F5,#DB0ADB,#635A63,#FF5733,#DAF7A6,#900C3F,#5F5CD3";
                      chartConfigs.dataSource.chart.showLabels = "0";
                      ReactDOM.unmountComponentAtNode(document.getElementById('top'));
 
                      ReactDOM.render( < ReactFC {...chartConfigs
                     }
                     />,
                     document.getElementById("top")
                      );
 
                      break;
 
                    case "labeltype":
                      chartConfigs.dataSource.chart.caption = "Top Global Oil Reserves";
                      chartConfigs.dataSource.chart.subCaption = "[2015-16]";
 
                      delete chartConfigs.dataSource.chart.paletteColors;
                      chartConfigs.dataSource.chart.showLabels = "1";
 
                      ReactDOM.unmountComponentAtNode(document.getElementById('top'));
                   ReactDOM.render( < ReactFC {...chartConfigs
                     }
                     />,
                        document.getElementById("top")
                      );
                      break;
                  }
             });
              }
         }
       });
This will render four radio buttons below the chart, allowing you to choose from the caption, sub-caption, palette colors, and show labels attributes to update at runtime. Again, the ReactDOM.render() method calls the reusable react component.

Changing the Chart Data

To update the chart data at runtime, copy the following code and paste it in your JS file:
const thirdElement = (
   <div id='dataedit'>
          <textarea id='data' rows="9" editable cols="40"></textarea><br />
          <button type="button" id='dataChange' class='btn-primary btn-sm'>Change Data</button>
      </div>
  );
  document.getElementById("ss").addEventListener("click", function() {
      refreshChart();
      console.log(this.getAttribute('id'));
      //console.log(thirdElement.props.children[0].props);
  
      ReactDOM.unmountComponentAtNode(document.getElementById('controllers'))
      ReactDOM.render(thirdElement, document.getElementById("controllers"));
 
      document.getElementById("data").value = JSON.stringify(myDataSource.data);
  
      console.log(document.getElementById("dataChange"));
      document.getElementById("dataChange").addEventListener("click", function() {
       var d = document.getElementById("data").value;
          chartConfigs.dataSource.data = JSON.parse(d);
          ReactDOM.unmountComponentAtNode(document.getElementById('top'))
          ReactDOM.render( < ReactFC {...chartConfigs}/>,
          document.getElementById("top") );
          console.log(d);
   });
 });
This will render the chart data in a text box below the chart. Edit the chart data and click Change Data to update the chart data at runtime. Similar to the previous two examples, calling the reusable component will re-render the chart’s basic configuration.

Rendering the Chart

Rendering the chart by calling the function Finally, to render the chart, copy the following code and paste it in your JS file:
var MyApp = React.createClass({
        render: function() {
          return ( <div id = "chart-container" > </div>
       );
     }
   });

Output

Here’s how the chart will finally look.
In the result section, click any options listed in the pane on the left to see how the sample works. If you see any errors in your code or have trouble executing the above sample, click here for the complete source code of the sample we have created for this tutorial. Read more on creating charts in ReactJS.
Jonathan and Soumya Dutta

Recent Posts

Announcing FusionCharts v4.1: Elevate Your Data Visualization Experience!

We’re excited to announce the upcoming release of FusionCharts v4.1—a groundbreaking step forward in the…

2 days ago

Bubble Maps: Visualizing Data Like Never Before

Have you ever been overwhelmed by a massive data set and wondered, "How do I…

1 week ago

Stock Charts: Mastering the Art of Visualizing Financial Data

If you’ve ever tried to make sense of the stock market, you’ve probably come across…

3 weeks ago

What is a Bar Chart Used For?

Imagine you’re comparing the sales performance of your top product lines across different regions, or…

2 months ago

AI-Powered Documentation for Data Visualization & Analytics

Have you ever spent hours buried in documentation, hunting for a specific piece of code?…

3 months ago

Unveiling the Hidden Gems: Top 5 AI Data Visualization Tools for 2024

Do you feel like your data is a cryptic puzzle, locked away from revealing its…

4 months ago