ECharts with React and TypeScript: A Comprehensive Guide

ECharts is a powerful open - source JavaScript charting library developed by Baidu. It offers a wide range of interactive and visually appealing charts, such as bar charts, line charts, pie charts, and more. React is a popular JavaScript library for building user interfaces, and TypeScript is a typed superset of JavaScript that adds static type checking. Combining ECharts with React and TypeScript allows developers to create highly maintainable and interactive charting applications. In this blog, we will explore the fundamental concepts, usage methods, common practices, and best practices of using ECharts with React and TypeScript.

Table of Contents

  1. Fundamental Concepts
    • What is ECharts?
    • What is React?
    • What is TypeScript?
    • Why Combine Them?
  2. Setting Up the Project
  3. Using ECharts in a React - TypeScript Project
    • Installation
    • Basic Usage
  4. Common Practices
    • Responsive Charts
    • Data Update
  5. Best Practices
    • Code Organization
    • Error Handling
  6. Conclusion
  7. References

1. Fundamental Concepts

What is ECharts?

ECharts is a JavaScript library that provides a variety of chart types, including but not limited to bar charts, line charts, scatter plots, and maps. It supports rich interactive features like data zooming, tooltip display, and data highlighting. ECharts uses SVG or Canvas rendering, which makes it suitable for both desktop and mobile applications.

What is React?

React is a JavaScript library for building user interfaces. It uses a component - based architecture, which allows developers to break down the UI into small, reusable components. React uses a virtual DOM to optimize rendering performance and provides a declarative way to describe UI.

What is TypeScript?

TypeScript is a superset of JavaScript that adds static type checking. It helps catch errors early in the development process, improves code readability, and enables better tooling support. TypeScript code is transpiled to plain JavaScript before running in the browser.

Why Combine Them?

Combining ECharts, React, and TypeScript offers several benefits. React’s component - based architecture makes it easy to manage and reuse ECharts charts in different parts of the application. TypeScript’s type checking ensures that the data passed to ECharts is in the correct format, reducing runtime errors.

2. Setting Up the Project

First, make sure you have Node.js and npm installed on your machine. Then, create a new React - TypeScript project using Create React App:

npx create-react-app my - echarts - project --template typescript
cd my - echarts - project

3. Using ECharts in a React - TypeScript Project

Installation

Install the ECharts library and the React wrapper for ECharts:

npm install echarts echarts - for - react

Basic Usage

Here is a simple example of creating a bar chart using ECharts in a React - TypeScript project:

import React from 'react';
import ReactECharts from 'echarts - for - react';

const BarChart: React.FC = () => {
    const option = {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [120, 200, 150, 80, 70, 110, 130],
                type: 'bar'
            }
        ]
    };

    return <ReactECharts option={option} />;
};

export default BarChart;

You can use this BarChart component in your App.tsx file:

import React from 'react';
import BarChart from './BarChart';

const App: React.FC = () => {
    return (
        <div className="App">
            <BarChart />
        </div>
    );
};

export default App;

4. Common Practices

Responsive Charts

To make the ECharts chart responsive, you can use the style prop of the ReactECharts component and listen for window resize events.

import React, { useEffect, useRef } from 'react';
import ReactECharts from 'echarts - for - react';

const ResponsiveBarChart: React.FC = () => {
    const chartRef = useRef<ReactECharts>(null);

    useEffect(() => {
        const handleResize = () => {
            if (chartRef.current) {
                chartRef.current.getEchartsInstance().resize();
            }
        };

        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    const option = {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [120, 200, 150, 80, 70, 110, 130],
                type: 'bar'
            }
        ]
    };

    return <ReactECharts ref={chartRef} option={option} style={{ width: '100%', height: '400px' }} />;
};

export default ResponsiveBarChart;

Data Update

To update the chart data, you can change the option prop of the ReactECharts component.

import React, { useState } from 'react';
import ReactECharts from 'echarts - for - react';

const UpdatableBarChart: React.FC = () => {
    const [newData, setNewData] = useState<number[]>([120, 200, 150, 80, 70, 110, 130]);

    const handleDataUpdate = () => {
        const updatedData = newData.map((val) => val + 10);
        setNewData(updatedData);
    };

    const option = {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: newData,
                type: 'bar'
            }
        ]
    };

    return (
        <div>
            <ReactECharts option={option} />
            <button onClick={handleDataUpdate}>Update Data</button>
        </div>
    );
};

export default UpdatableBarChart;

5. Best Practices

Code Organization

Separate the ECharts option configuration into a separate file or function. This makes the code more modular and easier to maintain.

// barChartOptions.ts
import { EChartsOption } from 'echarts';

export const getBarChartOptions = (data: number[]): EChartsOption => {
    return {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data,
                type: 'bar'
            }
        ]
    };
};
// BarChart.tsx
import React from 'react';
import ReactECharts from 'echarts - for - react';
import { getBarChartOptions } from './barChartOptions';

const BarChart: React.FC = () => {
    const data = [120, 200, 150, 80, 70, 110, 130];
    const option = getBarChartOptions(data);

    return <ReactECharts option={option} />;
};

export default BarChart;

Error Handling

When using ECharts, it’s important to handle errors gracefully. For example, if the data passed to ECharts is in an incorrect format, it may cause the chart to fail to render. You can add some validation logic before passing the data to the option object.

import { EChartsOption } from 'echarts';

const validateData = (data: number[]): boolean => {
    return Array.isArray(data) && data.every((val) => typeof val === 'number');
};

export const getBarChartOptions = (data: number[]): EChartsOption | null => {
    if (!validateData(data)) {
        console.error('Invalid data format for bar chart');
        return null;
    }

    return {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data,
                type: 'bar'
            }
        ]
    };
};

6. Conclusion

In this blog, we have explored how to use ECharts with React and TypeScript. We covered the fundamental concepts, setting up the project, basic usage, common practices like responsive charts and data update, and best practices for code organization and error handling. By combining these technologies, developers can create high - quality, interactive, and maintainable charting applications.

7. References