echarts-for-react

repository·master·Indexed 26 days ago

https://github.com/hustcc/echarts-for-react

A React wrapper for Apache ECharts (version 3.0.6) that provides the ReactECharts and ReactEChartsCore components for integrating data visualizations into React applications. It includes support for custom ECharts versions, manual module imports to reduce bundle size for ECharts v5 or v6, and specific configuration guidance for Next.js.

Tokens
3.3K
Snippets
10
Records
15
Agent score
88%

What's inside echarts-for-react

  1. Configure Next.js for echarts-for-react

    master

    Next.js users must enable code transpilation for echarts and zrender.

    For Next.js 13.1 or higher: Add transpilePackages: ['echarts', 'zrender'] to your next.config.js.

    For Next.js < 13.1: Use next-transpile-modules.

    // next.config.js for Next.js 13.1+
    /** @type {import('next').NextConfig} */
    
    const nextConfig = {
      // ...existing properties,
      transpilePackages: ['echarts', 'zrender'],
    }
    
    module.exports = nextConfig
    // next.config.js for Next.js < 13.1
    const withTM = require("next-transpile-modules")(["echarts", "zrender"]);
    
    module.exports = withTM({})
  2. Reduce bundle size by importing ECharts modules manually (v5 or v6)

    master

    To reduce bundle size in ECharts v5 or v6, use ReactEChartsCore from echarts-for-react/lib/core and manually import required modules from echarts/core, echarts/charts, echarts/components, and echarts/renderers.

    import React from 'react';
    // import the core library.
    import ReactEChartsCore from 'echarts-for-react/lib/core';
    // Import the echarts core module, which provides the necessary interfaces for using echarts.
    import * as echarts from 'echarts/core';
    // Import charts, all with Chart suffix
    import {
      BarChart,
    } from 'echarts/charts';
    // Import components, all suffixed with Component
    import {
      GridComponent,
      TooltipComponent,
      TitleComponent,
      DatasetComponent,
    } from 'echarts/components';
    // Import renderer, note that introducing the CanvasRenderer or SVGRenderer is a required step
    import {
      CanvasRenderer,
    }
     from 'echarts/renderers';
    
    // Register the required components
    echarts.use(
      [TitleComponent, TooltipComponent, GridComponent, BarChart, CanvasRenderer]
    );
    
    // The usage of ReactEChartsCore are same with above.
    <ReactEChartsCore
      echarts={echarts}
      option={this.getOption()}
      notMerge={true}
      lazyUpdate={true}
      theme={"theme_name"}
      onChartReady={this.onChartReadyCallback}
      onEvents={EventsDict}
      opts={}
    />
  3. Install echarts-for-react and echarts

    master

    Install echarts-for-react and its peer dependency echarts using npm. You can use your own version of echarts.

    $ npm install --save echarts-for-react
    
    # `echarts` is the peerDependence of `echarts-for-react`, you can install echarts with your own version.
    $ npm install --save echarts
  4. Resolve 'Component series.scatter3D not exists' error

    master

    If you encounter the error Component series.scatter3D not exists. Load it first., it means you are attempting to use a GL-based chart type without the necessary extension. To resolve this, install the echarts-gl package and import it in your project to register the GL components.

    npm install --save echarts-gl
    import 'echarts-gl'
    import ReactECharts from "echarts-for-react";
    
    <ReactECharts
      option={GL_OPTION}
    />
  5. Render charts using SVG in ECharts 4.x

    master

    To render a chart using the SVG renderer instead of the default Canvas renderer when using ECharts 4.x, pass the renderer: 'svg' configuration via the opts prop of the ReactECharts component.

    <ReactECharts
      option={this.getOption()}
      style={{height: '300px'}}
      opts={{renderer: 'svg'}} // use svg to render the chart.
    />
  6. Use ReactECharts component

    master

    To render an ECharts chart in a React application, import ReactECharts from echarts-for-react and pass an option object containing your ECharts configuration to the component.

    import React from 'react';
    import ReactECharts from 'echarts-for-react';
    
    const Page: React.FC = () => {
      const options = {
        grid: { top: 8, right: 8, bottom: 24, left: 36 },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true,
          },
        ],
        tooltip: {
          trigger: 'axis',
        },
      };
    
      return <ReactECharts option={options} />;
    };
    
    export default Page;
  7. Access the ECharts instance via getEchartsInstance()

    master

    Use a ref to access the ReactECharts component instance, then call .getEchartsInstance() to obtain the underlying ECharts object. This allows you to use any native ECharts API (e.g., resize(), getDataURL(), setOption()).

    // Using useRef with TypeScript
    const getOption = () => {/** */};
    
    export default function App() {
    	const echartsRef = useRef<InstanceType<typeof ReactEcharts>>(null);
    
    	useEffect(() => {
    		if (echartsRef.current) {
    			const echartsInstance = echartsRef.current.getEchartsInstance();
    			// do something
    			echartsInstance.resize();
    		}
    	}, []);
    
    	return <ReactEcharts ref={echartsRef} option={getOption()} />;
    }
  8. Configure the `opts` property in EChartsReactProps

    master

    The opts prop allows you to pass specific rendering and environment configurations to the underlying ECharts instance. Available keys include:

    • devicePixelRatio: The device pixel ratio.
    • renderer: The rendering engine, either 'canvas' or 'svg'.
    • width: The width of the container (number, null, undefined, or 'auto').
    • height: The height of the container (number, null, undefined, or 'auto').
    • locale: The locale string for ECharts.
  9. ReactECharts Props Reference

    master

    The following props are available for the ReactECharts component:

    • option (required, object): The ECharts option configuration.
    • notMerge (optional, boolean): When true, setOption will not merge the new data with the old data. Default is false.
    • replaceMerge (optional, string | string[]): Used with setOption to specify which components to replace.
    • lazyUpdate (optional, boolean): When true, setOption will lazy update the data. Default is false.
    • style (optional, object): The style of the ECharts div. Default is {height: '300px'}.
    • className (optional, string): The CSS class for the ECharts div.
    • theme (optional, string): The name of the registered ECharts theme.
    • onChartReady (optional, function): Callback function triggered when the chart is ready. Receives the echarts instance as a parameter.
    • loadingOption (optional, object): The ECharts loading option configuration.
    • showLoading (optional, boolean): Whether to show the loading mask while rendering. Default is false.
    • onEvents (optional, Record<string, Function>): An object mapping ECharts event names to callback functions. Callbacks receive the ECharts event object and the ECharts instance.
    • opts (optional, object): Configuration passed to echarts.init. For example, {renderer: 'svg'} to use SVG rendering.
    • autoResize (optional, boolean): Whether to trigger resize when the window resizes. Default is true.
  10. Configure EChartsReactProps

    master

    The EChartsReactProps type defines the configuration options for the React component. Key props include:

    • option: The ECharts configuration object.
    • echarts: The echarts library entry (useful for ensuring necessary imports are present).
    • theme: The theme configuration, which can be a theme name string or a theme object.
    • notMerge: Whether to not merge new options with old ones (default: false).
    • replaceMerge: Configuration for merging options (default: null).
    • lazyUpdate: Whether to use lazy update (default: false).
    • showLoading: Whether to show the loading animation (default: false).
    • loadingOption: Configuration for the loading animation (default: null).
    • opts: Additional ECharts options (default: {}).
    • onChartReady: Callback function triggered after the chart is rendered, receiving the EChartsInstance.
    • onEvents: An object mapping event names to handler functions (default: {}).
    • shouldSetOption: A function to determine if the ECharts options should be updated based on prop changes.
    • autoResize: Whether the chart should automatically resize when the window resizes.