How to encapsulate Echarts in React?

There are multiple methods to encapsulate Echarts in React, with one common way being:

  1. First, install the Echarts library.
npm install echarts --save
  1. JavaScript module named EchartsComponent.js
import React, { useEffect, useRef } from 'react';
import echarts from 'echarts';

const EchartsComponent = ({ options }) => {
  const chartRef = useRef(null);

  useEffect(() => {
    const chart = echarts.init(chartRef.current);
    chart.setOption(options);

    return () => {
      chart.dispose();
    };
  }, [options]);

  return <div ref={chartRef} style={{ width: '100%', height: '300px' }} />;
};

export default EchartsComponent;
  1. An Echarts component
import React from 'react';
import EchartsComponent from './EchartsComponent';

const ParentComponent = () => {
  const options = {
    // Echarts配置项
    // ...
  };

  return (
    <div>
      <h1>使用Echarts的父组件</h1>
      <EchartsComponent options={options} />
    </div>
  );
};

export default ParentComponent;

In the example above, the EchartsComponent receives an options parameter to configure the chart options of Echarts. A DOM reference is created using useRef, and useEffect is used to initialize the Echarts instance and set the options when the component mounts and when the options change. The Echarts instance is cleaned up when the component unmounts using a function in the return statement.

In this way, we can encapsulate Echarts in React and render different charts by passing different options through the component’s props.

bannerAds