Getting Started with CanvasJS React Component

Due to the increasing popularity of React in web application development, we thought of creating a React Component for CanvasJS Charts & publish it on NPM. This allows you to seamlessly integrate CanvasJS Charts into your React based Applications. Below is how you can get started with the same.

In case you have any suggestions/feedback please post it in our forum.

Here are couple of things that you need to remember while using React Chart Component.

  1. You no longer have to call render() method during the initial render. You need to call render() only when chart options change.
  2. You can get reference to the chart instance by passing onRef = {ref => this.chart = ref} props to the component. This allows you to access all chart properties and methods including render().
  3. Once you get reference to the chart object, you can update any of the options – like chart.options.data[0].type = “column” and call chart.render(). Refer Updating Chart Options / Data for more information.
  4. You can also style the chart component shown below.
  5. <CanvasJSChart options={options} containerProps={{ width: '100%', height: '300px' }} />
    

Step-By-Step Instruction

1. Create a React App

As a first step, create a react app. Refer documentation on Creating a New React App for more info.

2. Install CanvasJS React Charts via NPM

Install CanvasJS React Charts package via npm by running the following command.

npm install @canvasjs/react-charts

3. Import CanvasJS React Charts

Import CanvasJS React Charts to your application.

import CanvasJSReact from '@canvasjs/react-charts';
//var CanvasJSReact = require('@canvasjs/react-charts');

var CanvasJS = CanvasJSReact.CanvasJS;
var CanvasJSChart = CanvasJSReact.CanvasJSChart;

Once the package is imported, you are ready to go. Now you can add CanvasJSChart component with chart-options & container-style as props and onRef as optional props – that you can pass when you need reference to the chart instance.

class App extends Component {	
  render() {
    const options = {
      title: {
        text: "Basic Column Chart in React"
      },
      data: [{				
        type: "column",
        dataPoints: [
          { label: "Apple",  y: 10  },
          { label: "Orange", y: 15  },
          { label: "Banana", y: 25  },
          { label: "Mango",  y: 30  },
          { label: "Grape",  y: 28  }
        ]
      }]
    }
		
    return (
      <div>
        <CanvasJSChart options = {options}
          /* onRef = {ref => this.chart = ref} */
        />
        </div>
    );
  }
}
Note:
  • React requires polyfills to run on older browsers such as IE 9 and IE 10.

Have a look into our reference section for complete set of options that are available. In order to make it simpler we have also created various examples, please check React Chart Gallery for the same.


If you have any questions, please feel free to ask in our forums.Ask Question