The introduction

In the development of the project, for us front-end developers, there is always an unavoidable need for visual analysis and design of data. However, in fact, it is extremely difficult to quickly create simple, beautiful and cool visualizations with poor maintainability if only relying on Html5 Canvas. Nowadays, with the iterative development of technology, there have been many reliable, easy to use, easy to operate, interactive and cross-platform visualization solutions such as ECharts, HighCharts, chart.js and so on. In this article, we use ECharts as an example to try to apply a visual solution to React, one of the most popular front-end frameworks. React offers superior performance and high flexibility, while ECharts is better in practicality and performance than its competitors. Therefore, the use of these two stacks is still in high demand, and it is common to apply ECharts to React projects.

I. Preparation before development

In the original JS application or jQuery project, we usually download the core JS file directly from the official website and import it into our project. However, in the React project, we don’t need to download the core JS file directly, because the React project development has a secondary packaging based on Webpack. Webpack is a front-end project deployment and packaging tool based on Node.js. In short, React project development is based on nodeJS environment. You don’t have to worry about the details.

Specific operation process

1.NPM i-s Echarts/YARN Add Echarts download and install Echarts into the project through NPM/YARN package manager: NPM i-s Echarts/YARN Add Echarts2.The paradigm used to introduce ECharts into the React component we wrote:import React, {
	Component
} from "react";
// Introduce the ECharts main module
import * as echarts from "echarts/lib/echarts";
// Import Echart modules as needed.class APP extends Component {
	componentDidMount() {
		// Initialize the echarts instance and mount it to the DOM element with the id main for display
		var myChart = echarts.init(document.getElementById("main"));
		// Draw a diagram
		myChart.setOption({
			...
		});
	}
	render() { // Render requires the container element of the Echart instance to be aged
		return <div id = "main"
		style = {
			{
				width: 400.height: 400}} > < /div>; }}export default APP;
Copy the code

Second, the case

1. Draw the heart through polar coordinates and double numerical axes

Final effect

Thought analysis

1.Create a React component and require the state, render function, and componentDidMount hook within the component2.The render function needs to render the container element that holds the Echart instance and declare the ID so that the Echarts instance can find the target to mount3.Set the state state within the component and define the sourceData data source to hold the Echarts instance3.ComponentDidMount The componentDidMount hook, called after the Render function has rendered a container element, does the following:1) generates the coordinate data source and updates it to sourceData in state2Initialize the Echarts instance and mount it on the div element with id main3) Through mychart.setoption (OBJ), integrate the data to be displayed into an OBJ object, including sourceData, and draw love graphicsCopy the code

The demo source code

import React, { Component} from "react";
// Introduce the ECharts main module
import * as echarts from "echarts/lib/echarts";
// Introduce the modules needed for the line chart
import "echarts/lib/chart/line";
import "echarts/lib/component/title";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/legend";
import 'echarts/lib/component/polar';
class App extends Component { // Initialization state
    state = {
        sourceData: [],};async componentDidMount() {
        let data = [];
        for (let i = 0; i <= 100; i++) {// According to the formula, generate the coordinate data source array drawn on the graph
            let theta = i / 100 * 360;
            let r = 5 * (1 + Math.sin(theta / 180 * Math.PI));
            data.push([r, theta]);
        }
        this.setState(() = > {
            return {
                sourceData: data// Update the react component's state data
            };
        });
        // Initialize the Echarts instance and mount it to the DOM element with the id main for display
        let myChart = echarts.init(document.getElementById("main"));
        // Draw the data needed for the Echarts instance
        myChart.setOption({
                title: {
                    text: 'Polar double numerical axis'
                },
                legend: {
                    data: ['line']},polar: {},
                tooltip: {
                    trigger: 'axis'.axisPointer: {
                        type: 'cross'}},angleAxis: {
                    type: 'value'.startAngle: 0
                },
                radiusAxis: {},series: [{
                    coordinateSystem: 'polar'.// Polar coordinates
                    name: 'line'.type: 'line'.data: data // Draw the heart graph according to the generated coordinate array}}]); }render() {// Render requires the container element of the Echart instance to be aged
            return <div id = "main" style = { {  width: 1000.height: 600}} > </div>; }}export default App; 
Copy the code

2. Nightingale Rose Chart data display

Final effect

Thought analysis

1.Create a React component and require the state, render function, and componentDidMount hook within the component2.The render function needs to render the container element that holds the Echart instance and declare the ID so that the Echarts instance can find the target to mount3.Set the state state within the component and define the sourceData data source to hold the Echarts instance3.ComponentDidMount The componentDidMount hook, called after the Render function has rendered a container element, does the following:1Initialize the Echarts instance and mount it on the div element with id main2) Through mychart.setoption (OBJ), integrate the data to be displayed, including state data and cellData, into an OBJ object and draw a chart.Copy the code

The demo source code

import React, {
    Component
} from "react";
// Introduce the ECharts main module
import * as echarts from "echarts/lib/echarts";
// Import the required modules for the pie chart
import "echarts/lib/chart/pie";
import "echarts/lib/component/title";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/legend";
class App extends Component { // Initialization state
    state = {
        data: [{value: 150.name: 'Chinese'},
            {value: 110.name: 'physical'},
            {value: 150.name: 'mathematics'},
            {value: 100.name: 'chemistry'},
            {value: 150.name: 'English'},
            {value: 90.name: 'biological'},].celldata: ['Chinese'.'physical'.'mathematics'.'chemistry'.'English'.'biological']};async componentDidMount() {
        
        var myChart = echarts.init(document.getElementById("main"));
        myChart.setOption(
            {
                title: {
                    text: 'Proportion of Science Scores in gaokao'.left: 'center'
                },
                tooltip: {
                    trigger: 'item'.formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                legend: {
                    left: 'center'.top: 'bottom'.data: this.state.celldata
                },
                toolbox: {
                    show: true.feature: {
                        mark: {show: true},
                        dataView: {show: true.readOnly: false},
                        magicType: {
                            show: true.type: ['pie'.'funnel']},restore: {show: true},
                        saveAsImage: {show: true}}},series: [{name: 'scores'.type: 'pie'.radius: [30.110].center: ['50%'.'50%'].roseType: 'area'.data: this.state.data
                    }
                ]
            }            
        );
    }
    render() {
            return <div id = "main" style = { {  width: 1000.height: 400}} > </div>; }}export default App; 
Copy the code