### Running the Development Server for echarts-for-react Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Provides instructions to clone the repository, install dependencies, and start the development server for the echarts-for-react project. This is useful for local development and testing. ```bash git clone git@github.com:hustcc/echarts-for-react.git npm install npm start ``` -------------------------------- ### Install echarts-for-react and echarts Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Installs the echarts-for-react library and its peer dependency, echarts, using npm. Ensure you have Node.js and npm installed. ```bash npm install --save echarts-for-react npm install --save echarts ``` -------------------------------- ### Web GL 3D Scatter Plot Example Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/gl.md Demonstrates how to create a basic 3D scatter plot using ECharts for React with the 'echarts-gl' extension. ```APIDOC ## Web GL 3D Scatter Plot Example ### Description This example shows how to render a 3D scatter plot using `echarts-for-react` by importing and utilizing the `echarts-gl` extension. ### Method N/A (This is a client-side rendering example) ### Endpoint N/A ### Parameters N/A ### Request Example ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; import 'echarts-gl'; const Page: React.FC = () => { const option = { grid3D: {}, xAxis3D: {}, yAxis3D: {}, zAxis3D: {}, series: [{ type: 'scatter3D', symbolSize: 50, data: [[-1, -1, -1], [0, 0, 0], [1, 1, 1]], itemStyle: { opacity: 1 } }] }; return ; }; export default Page; ``` ### Response N/A (Client-side rendering) ``` -------------------------------- ### Basic React Component Usage with echarts-for-react Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Demonstrates how to import and use the ReactECharts component to render ECharts options within a React application. This requires the echarts-for-react library to be installed. ```typescript import ReactECharts from 'echarts-for-react'; // render echarts option. ``` -------------------------------- ### Implement 3D Charts with echarts-gl Source: https://context7.com/hustcc/echarts-for-react/llms.txt Allows the creation of 3D visualizations by importing the `echarts-gl` library. This enables support for various 3D chart types such as `scatter3D`, `bar3D`, `surface`, and `globe`. Ensure `echarts-gl` is installed and imported to use these features. ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; import 'echarts-gl'; const Chart3D: React.FC = () => { const option = { grid3D: {}, xAxis3D: { type: 'value' }, yAxis3D: { type: 'value' }, zAxis3D: { type: 'value' }, series: [{ type: 'scatter3D', symbolSize: 50, data: [ [-1, -1, -1], [0, 0, 0], [1, 1, 1], [2, 0, 1], [0, 2, 1] ], itemStyle: { opacity: 0.8 } }] }; return ( ); }; export default Chart3D; ``` -------------------------------- ### Access ECharts Instance via Refs Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Provides examples for accessing the underlying ECharts instance to call native ECharts APIs, using both class-based refs and functional component hooks. ```typescript // Class component approach { this.echartRef = e; }} option={this.getOption()} /> const echartInstance = this.echartRef.getEchartsInstance(); const base64 = echartInstance.getDataURL(); ``` ```typescript // Functional component with useRef const echartsRef = useRef>(null); useEffect(() => { if (echartsRef.current) { const echartsInstance = echartsRef.current.getEchartsInstance(); echartsInstance.resize(); } }, []); ``` -------------------------------- ### Register and Apply Custom Themes in React Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/theme.md This example demonstrates registering two distinct themes using echarts.registerTheme and toggling between them dynamically in a React component. It utilizes the ReactECharts component's theme prop to update the visual appearance of the chart based on state. ```tsx import React, { useState } from 'react'; import * as echarts from 'echarts'; import ReactECharts from 'echarts-for-react'; echarts.registerTheme('my_theme', { backgroundColor: '#f4cccc', }); echarts.registerTheme('another_theme', { backgroundColor: '#eee', }); const Page: React.FC = () => { const option = { title: { text: '阶梯瀑布图' }, xAxis: { type: 'category', data: ['11月1日', '11月2日'] }, yAxis: { type: 'value' }, series: [{ type: 'bar', data: [900, 345] }] }; const [theme, setTheme] = useState(); function toggleTheme() { setTheme(theme === 'my_theme' ? 'another_theme' : 'my_theme'); } return ( <> ); }; export default Page; ``` -------------------------------- ### Bind ECharts Events in React Component Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/event.md This example shows how to configure event listeners for an ECharts instance in React. It utilizes the onEvents prop to map event names to handler functions and demonstrates state updates based on chart interactions. ```tsx import React, { useState } from 'react'; import ReactECharts from 'echarts-for-react'; const Page: React.FC = () => { const option = { title : { text: '某站点用户访问来源', subtext: '纯属虚构', x:'center' }, tooltip : { trigger: 'item', formatter: "{a}
{b} : {c} ({d}%)" }, legend: { orient: 'vertical', left: 'left', data: ['直接访问','邮件营销','联盟广告','视频广告','搜索引擎'] }, series : [ { name: '访问来源', type: 'pie', radius : '55%', center: ['50%', '60%'], data:[ {value:335, name:'直接访问'}, {value:310, name:'邮件营销'}, {value:234, name:'联盟广告'}, {value:135, name:'视频广告'}, {value:1548, name:'搜索引擎'} ] } ] }; const [count, setCount] = useState(0); function onChartReady(echarts) { console.log('echarts is ready', echarts); } function onChartClick(param, echarts) { console.log(param, echarts); setCount(count + 1); }; function onChartLegendselectchanged(param, echarts) { console.log(param, echarts); }; return ( ); }; ``` -------------------------------- ### Dynamic Data Updates for ECharts Charts in React Source: https://context7.com/hustcc/echarts-for-react/llms.txt This example demonstrates how to update ECharts charts dynamically in React by modifying the `option` prop. It uses React's `useState` and `useEffect` hooks to manage data and simulate real-time updates. For efficient change detection, immutable updates are recommended. ```tsx import React, { useState, useEffect } from 'react'; import ReactECharts from 'echarts-for-react'; const RealTimeChart: React.FC = () => { const [data, setData] = useState([820, 932, 901, 934, 1290, 1330, 1320]); const [labels, setLabels] = useState(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']); useEffect(() => { const timer = setInterval(() => { const newValue = Math.round(Math.random() * 1000 + 500); const newLabel = new Date().toLocaleTimeString(); setData(prev => [...prev.slice(1), newValue]); setLabels(prev => [...prev.slice(1), newLabel]); }, 2000); return () => clearInterval(timer); }, []); const option = { title: { text: 'Real-Time Data' }, tooltip: { trigger: 'axis' }, xAxis: { type: 'category', data: labels }, yAxis: { type: 'value' }, series: [{ data: data, type: 'line', smooth: true, areaStyle: {} }] }; return ; }; export default RealTimeChart; ``` -------------------------------- ### Apply French Locale to ECharts Component Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/locale.md This example shows how to import a specific language file from ECharts and pass the locale option to the ReactECharts component. It ensures that UI components like the toolbox display labels in the specified language. ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; import "echarts/i18n/langFR"; const Page: React.FC = () => { const option = { title: { text: 'ECharts 入门示例' }, toolbox: { feature: { saveAsImage: {}, dataZoom: {}, restore: {} } }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] }, yAxis: {}, series: [{ name: '销量', type: 'line', data: [5, 20, 36, 10, 10, 20] }] }; return ; }; export default Page; ``` -------------------------------- ### Resolve 'echarts-gl' Dependency for 3D Series in React Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md To use 3D chart types like scatter3D, install the 'echarts-gl' package and import it. This makes the necessary 3D components available to ECharts. ```bash npm install --save echarts-gl ``` ```typescript import 'echarts-gl' import ReactECharts from "echarts-for-react"; ``` -------------------------------- ### Pass HTML attributes to ReactECharts component Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/html-props.md This example demonstrates passing standard HTML attributes like 'role' and 'data-testid' to the ReactECharts component. These properties are automatically applied to the rendered container div, allowing for easier testing and accessibility integration. ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; const Page: React.FC = () => { const option = { title: { text: '堆叠区域图' }, tooltip: { trigger: 'axis' }, legend: { data:['邮件营销','联盟广告','视频广告'] }, xAxis: [{ type: 'category', boundaryGap: false, data: ['周一','周二','周三','周四','周五','周六','周日'] }], yAxis: [{ type: 'value' }], series: [ { name:'邮件营销', type:'line', stack: '总量', data:[120, 132, 101, 134, 90, 230, 210] }, { name:'联盟广告', type:'line', stack: '总量', data:[220, 182, 191, 234, 290, 330, 310] }, { name:'视频广告', type:'line', stack: '总量', data:[150, 232, 201, 154, 190, 330, 410] } ] }; return ( ); }; ``` -------------------------------- ### Dynamic Chart Update in React Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/dynamic.md This React component utilizes echarts-for-react to display a dynamic chart. It initializes with a default option and then updates the chart data at regular intervals using `setInterval` and `useState` to manage the chart's option. The `useEffect` hook handles the interval setup and cleanup. Dependencies include `react`, `echarts-for-react`, and `lodash.clonedeep` for immutable state updates. ```tsx import React, { useState, useEffect } from 'react'; import ReactECharts from 'echarts-for-react'; import cloneDeep from 'lodash.clonedeep'; const Page: React.FC = () => { const DEFAULT_OPTION = { title: { text: 'Hello Echarts-for-react.', }, tooltip: { trigger: 'axis', }, legend: { data: ['最新成交价', '预购队列'], }, toolbox: { show: true, feature: { dataView: { readOnly: false }, restore: {}, saveAsImage: {}, }, }, grid: { top: 60, left: 30, right: 60, bottom: 90, }, dataZoom: { show: false, start: 0, end: 100, }, visualMap: { show: false, min: 0, max: 1000, color: [ '#BE002F', '#F20C00', '#F00056', '#FF2D51', '#FF2121', '#FF4C00', '#FF7500', '#FF8936', '#FFA400', '#F0C239', '#FFF143', '#FAFF72', '#C9DD22', '#AFDD22', '#9ED900', '#00E500', '#0EB83A', '#0AA344', '#0C8918', '#057748', '#177CB0', ], }, xAxis: [ { type: 'category', boundaryGap: true, data: (function () { let now = new Date(); let res = []; let len = 50; while (len--) { res.unshift(now.toLocaleTimeString().replace(/^\D*/, '')); now = new Date(now - 2000); } return res; })(), }, { type: 'category', boundaryGap: true, data: (function () { let res = []; let len = 50; while (len--) { res.push(50 - len + 1); } return res; })(), }, ], yAxis: [ { type: 'value', scale: true, name: '价格', max: 20, min: 0, boundaryGap: [0.2, 0.2], }, { type: 'value', scale: true, name: '预购量', max: 1200, min: 0, boundaryGap: [0.2, 0.2], }, ], series: [ { name: '预购队列', type: 'bar', xAxisIndex: 1, yAxisIndex: 1, itemStyle: { normal: { barBorderRadius: 4, }, }, animationEasing: 'elasticOut', animationDelay: function (idx) { return idx * 10; }, animationDelayUpdate: function (idx) { return idx * 10; }, data: (function () { let res = []; let len = 50; while (len--) { res.push(Math.round(Math.random() * 1000)); } return res; })(), }, { name: '最新成交价', type: 'line', data: (function () { let res = []; let len = 0; while (len < 50) { res.push((Math.random() * 10 + 5).toFixed(1) - 0); len++; } return res; })(), }, ], }; let count; const [option, setOption] = useState(DEFAULT_OPTION); function fetchNewData() { const axisData = new Date().toLocaleTimeString().replace(/^\D*/, ''); const newOption = cloneDeep(option); // immutable newOption.title.text = 'Hello Echarts-for-react.' + new Date().getSeconds(); const data0 = newOption.series[0].data; const data1 = newOption.series[1].data; data0.shift(); data0.push(Math.round(Math.random() * 1000)); data1.shift(); data1.push((Math.random() * 10 + 5).toFixed(1) - 0); newOption.xAxis[0].data.shift(); newOption.xAxis[0].data.push(axisData); newOption.xAxis[1].data.shift(); newOption.xAxis[1].data.push(count++); setOption(newOption); } useEffect(() => { const timer = setInterval(() => { fetchNewData(); }, 1000); return () => clearInterval(timer); }); return ; }; export default Page; ``` -------------------------------- ### Access ECharts Instance with getEchartsInstance() in React Source: https://context7.com/hustcc/echarts-for-react/llms.txt This snippet shows how to use a ref to get the underlying ECharts instance from echarts-for-react. This allows for advanced operations such as exporting charts as images or calling native ECharts API methods. It requires React's useRef hook and the echarts-for-react component. ```tsx import React, { useRef } from 'react'; import ReactECharts from 'echarts-for-react'; const ChartWithExport: React.FC = () => { const chartRef = useRef>(null); const option = { title: { text: 'Funnel Chart' }, tooltip: { trigger: 'item', formatter: '{a}
{b}: {c}%' }, legend: { data: ['Show', 'Click', 'Visit', 'Inquiry', 'Order'] }, series: [{ name: 'Funnel', type: 'funnel', left: '10%', width: '80%', data: [ { value: 60, name: 'Visit' }, { value: 40, name: 'Inquiry' }, { value: 20, name: 'Order' }, { value: 80, name: 'Click' }, { value: 100, name: 'Show' } ] }] }; function exportAsImage() { if (chartRef.current) { const echartInstance = chartRef.current.getEchartsInstance(); const base64 = echartInstance.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' }); // Open image in new window const img = new Image(); img.src = base64; const newWindow = window.open('', '_blank'); newWindow?.document.write(img.outerHTML); } } function resizeChart() { if (chartRef.current) { chartRef.current.getEchartsInstance().resize(); } } return ( <> ); }; export default ChartWithExport; ``` -------------------------------- ### Implement ReactECharts with Full Configuration Source: https://context7.com/hustcc/echarts-for-react/llms.txt Demonstrates the usage of the ReactECharts component with all available configuration options, including styling, loading states, event callbacks, and initialization parameters. ```typescript import React from 'react'; import ReactECharts from 'echarts-for-react'; import type { EChartsInstance } from 'echarts-for-react'; const FullPropsExample: React.FC = () => { const option = { xAxis: { type: 'category', data: ['A', 'B', 'C'] }, yAxis: { type: 'value' }, series: [{ type: 'bar', data: [10, 20, 30] }] }; return ( { console.log('Chart ready:', instance); }} onEvents={{ click: (params, instance) => console.log('Clicked:', params), mouseover: (params, instance) => console.log('Hover:', params) }} shouldSetOption={(prevProps, props) => { return prevProps.option !== props.option; }} /> ); }; export default FullPropsExample; ``` -------------------------------- ### Initialize ECharts with Options Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Demonstrates passing initialization options, such as the renderer type, to the ECharts instance via the opts prop. ```typescript ``` -------------------------------- ### Display Loading State with showLoading Source: https://context7.com/hustcc/echarts-for-react/llms.txt Demonstrates how to show a loading indicator while data is being fetched. The `showLoading` prop controls the visibility of the indicator, and `loadingOption` allows customization of its appearance, including text, color, and mask. This is useful for providing user feedback during asynchronous data operations. ```tsx import React, { useState, useEffect } from 'react'; import ReactECharts from 'echarts-for-react'; const ChartWithLoading: React.FC = () => { const [loading, setLoading] = useState(true); const [option, setOption] = useState({}); const loadingOption = { text: 'Loading data...', color: '#4413c2', textColor: '#270240', maskColor: 'rgba(255, 255, 255, 0.8)', zlevel: 0 }; useEffect(() => { // Simulate data fetching const timer = setTimeout(() => { setOption({ title: { text: 'Radar Chart' }, radar: { indicator: [ { name: 'Sales', max: 6500 }, { name: 'Admin', max: 16000 }, { name: 'IT', max: 30000 }, { name: 'Support', max: 38000 }, { name: 'Dev', max: 52000 } ] }, series: [{ type: 'radar', data: [{ value: [4300, 10000, 28000, 35000, 50000], name: 'Budget' }, { value: [5000, 14000, 28000, 31000, 42000], name: 'Actual' }] }] }); setLoading(false); }, 2000); return () => clearTimeout(timer); }, []); return ( ); }; export default ChartWithLoading; ``` -------------------------------- ### Basic ReactECharts Usage Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Demonstrates the fundamental way to use the ReactECharts component. It requires importing the library and passing an options object to configure the chart. Dependencies include React and the echarts-for-react library. ```typescript import React from 'react'; import ReactECharts from 'echarts-for-react'; // or var ReactECharts = require('echarts-for-react'); ``` -------------------------------- ### Basic Line Chart with ReactECharts Source: https://context7.com/hustcc/echarts-for-react/llms.txt Demonstrates how to render a basic line chart using the ReactECharts component. It takes an ECharts option object as a prop to define the chart's appearance and data. The component handles resizing and other chart lifecycle events automatically. ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; const BasicLineChart: React.FC = () => { const option = { title: { text: 'Sales Overview' }, tooltip: { trigger: 'axis' }, legend: { data: ['Email Marketing', 'Affiliate Ads', 'Video Ads'] }, xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { name: 'Email Marketing', type: 'line', stack: 'Total', areaStyle: {}, data: [120, 132, 101, 134, 90, 230, 210] }, { name: 'Affiliate Ads', type: 'line', stack: 'Total', areaStyle: {}, data: [220, 182, 191, 234, 290, 330, 310] }, { name: 'Video Ads', type: 'line', stack: 'Total', areaStyle: {}, data: [150, 232, 201, 154, 190, 330, 410] } ] }; return ; }; export default BasicLineChart; ``` -------------------------------- ### Configure Next.js for ECharts Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Shows how to configure next.config.js to transpile ECharts dependencies. Includes both modern Next.js transpilation and legacy support using next-transpile-modules. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['echarts', 'zrender'], } module.exports = nextConfig ``` ```javascript // next.config.js for Next.js < 13.1 const withTM = require("next-transpile-modules")(["echarts", "zrender"]); module.exports = withTM({}) ``` -------------------------------- ### Next.js Configuration for ECharts Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Provides guidance for Next.js users on configuring their project to transpile ECharts and ZRender modules. This is necessary for Next.js versions 13.1 and higher, where `next-transpile-modules` is deprecated. ```javascript // next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['echarts', 'zrender'] }; ``` -------------------------------- ### Configure SVG Renderer with opts Source: https://context7.com/hustcc/echarts-for-react/llms.txt Enables SVG rendering for charts, which offers better scalability and smaller file sizes for exports compared to the default Canvas renderer. This is configured using the `opts` prop with the `renderer` property set to 'svg'. Other options like `width`, `height`, and `locale` can also be specified. ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; const SVGChart: React.FC = () => { const option = { title: { text: 'SVG Rendered Chart' }, tooltip: {}, xAxis: { data: ['Shirts', 'Sweaters', 'Chiffon', 'Pants', 'Heels', 'Socks'] }, yAxis: {}, series: [{ name: 'Sales', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; return ( ); }; export default SVGChart; ``` -------------------------------- ### Register and Use ECharts Themes Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Demonstrates how to register a custom theme object with ECharts and apply it to the ReactECharts component via the theme prop. ```typescript import echarts from 'echarts'; echarts.registerTheme('my_theme', { backgroundColor: '#f4cccc' }); ``` -------------------------------- ### getEchartsInstance Method Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Access the underlying ECharts instance to perform native ECharts API operations. ```APIDOC ## getEchartsInstance() ### Description Retrieves the underlying ECharts instance object. This allows access to the full suite of native ECharts methods such as getDataURL, resize, or manual event binding. ### Usage ```javascript const echartInstance = this.echartRef.getEchartsInstance(); const base64 = echartInstance.getDataURL(); ``` ### Returns - **echartsInstance** (object) - The native ECharts instance. ``` -------------------------------- ### Configure Next.js for ECharts Transpilation Source: https://context7.com/hustcc/echarts-for-react/llms.txt Configures Next.js to properly transpile ECharts and ZRender modules, which is required for server-side rendering compatibility. The approach varies based on the Next.js version. ```javascript // next.config.js (Next.js 13.1+) /** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['echarts', 'zrender'] }; module.exports = nextConfig; ``` ```javascript // next.config.js (Next.js < 13.1) const withTM = require('next-transpile-modules')(['echarts', 'zrender']); module.exports = withTM({}); ``` -------------------------------- ### Render Force-Directed Graph in React Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/graph.md This snippet demonstrates the implementation of a force-directed graph component. It utilizes the ReactECharts wrapper to pass a complex configuration object containing nodes and categories to the ECharts engine. ```tsx import React from 'react'; import ReactECharts from 'echarts-for-react'; const Page: React.FC = () => { const webkitDep = { "type": "force", "categories": [ {"name": "HTMLElement", "keyword": {}, "base": "HTMLElement"}, {"name": "WebGL", "keyword": {}, "base": "WebGLRenderingContext"}, {"name": "SVG", "keyword": {}, "base": "SVGElement"}, {"name": "CSS", "keyword": {}, "base": "CSSRule"}, {"name": "Other", "keyword": {}} ], "nodes": [ {"name": "AnalyserNode", "value": 1, "category": 4}, {"name": "AudioNode", "value": 1, "category": 4} ] }; return ( ); }; ``` -------------------------------- ### Render Force-Directed Graph with ReactECharts Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/graph.md This snippet shows how to define an ECharts option object with a graph series and pass it to the ReactECharts component. It includes mapping node IDs and configuring force layout parameters like repulsion and gravity. ```javascript const option = { legend: { data: ['HTMLElement', 'WebGL', 'SVG', 'CSS', 'Other'] }, series: [{ type: 'graph', layout: 'force', animation: false, label: { normal: { position: 'right', formatter: '{b}' } }, draggable: true, data: webkitDep.nodes.map(function (node, idx) { node.id = idx; return node; }), categories: webkitDep.categories, force: { edgeLength: 5, repulsion: 20, gravity: 0.2 }, edges: webkitDep.links }] }; return ; ``` -------------------------------- ### Optimize Bundle Size with ReactEChartsCore Source: https://context7.com/hustcc/echarts-for-react/llms.txt Provides an optimized way to use ECharts in React applications by leveraging tree-shaking. `ReactEChartsCore` allows you to import only the necessary ECharts modules (charts, components, renderers), significantly reducing the final bundle size. This is highly recommended for production environments. ```tsx import React from 'react'; import ReactEChartsCore from 'echarts-for-react/lib/core'; import * as echarts from 'echarts/core'; import { BarChart, LineChart } from 'echarts/charts'; import { GridComponent, TooltipComponent, TitleComponent, LegendComponent, DatasetComponent } from 'echarts/components'; import { CanvasRenderer } from 'echarts/renderers'; // Register only the components you need echarts.use([ TitleComponent, TooltipComponent, GridComponent, LegendComponent, DatasetComponent, BarChart, LineChart, CanvasRenderer ]); const OptimizedChart: React.FC = () => { const option = { title: { text: 'Optimized Bundle Chart' }, tooltip: { trigger: 'axis' }, legend: { data: ['Sales', 'Profit'] }, xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4'] }, yAxis: { type: 'value' }, series: [ { name: 'Sales', type: 'bar', data: [120, 200, 150, 80] }, { name: 'Profit', type: 'line', data: [30, 50, 40, 20] } ] }; return ( ); }; export default OptimizedChart; ``` -------------------------------- ### Implement Chart Loading State with ECharts for React Source: https://github.com/hustcc/echarts-for-react/blob/master/docs/examples/loading.md This React component demonstrates how to display a loading state for an ECharts chart. It utilizes the `showLoading` prop to enable the loading indicator and `loadingOption` to customize its appearance. A `useEffect` hook simulates a delay before hiding the loading indicator using `echarts.hideLoading()`, which is called after a timeout. ```tsx import React, { useState, useEffect } from 'react'; import ReactECharts from 'echarts-for-react'; const Page: React.FC = () => { const option = { title: { text: '基础雷达图' }, tooltip: {}, legend: { data: ['预算分配(Allocated Budget)', '实际开销(Actual Spending)'] }, radar: { // shape: 'circle', indicator: [ { name: '销售(sales)', max: 6500}, { name: '管理(Administration)', max: 16000}, { name: '信息技术(Information Techology)', max: 30000}, { name: '客服(Customer Support)', max: 38000}, { name: '研发(Development)', max: 52000}, { name: '市场(Marketing)', max: 25000} ] }, series: [{ name: '预算 vs 开销(Budget vs spending)', type: 'radar', // areaStyle: {normal: {}}, data : [ { value : [4300, 10000, 28000, 35000, 50000, 19000], name : '预算分配(Allocated Budget)' }, { value : [5000, 14000, 28000, 31000, 42000, 21000], name : '实际开销(Actual Spending)' } ] }] }; let timer; useEffect(() => { return () => clearTimeout(timer); }); const loadingOption = { text: '加载中...', color: '#4413c2', textColor: '#270240', maskColor: 'rgba(194, 88, 86, 0.3)', zlevel: 0 }; function onChartReady(echarts) { timer = setTimeout(function() { echarts.hideLoading(); }, 3000); } return ; }; export default Page; ``` -------------------------------- ### Theme Configuration for ECharts Charts in React Source: https://context7.com/hustcc/echarts-for-react/llms.txt This snippet illustrates how to apply custom themes to ECharts charts rendered with echarts-for-react. It involves registering themes with the ECharts library using `echarts.registerTheme` and then applying them via the `theme` prop. Themes can be defined as objects or referenced by name. ```tsx import React, { useState } from 'react'; import * as echarts from 'echarts'; import ReactECharts from 'echarts-for-react'; // Register custom themes echarts.registerTheme('dark_theme', { backgroundColor: '#333', textStyle: { color: '#fff' }, title: { textStyle: { color: '#fff' } } }); echarts.registerTheme('light_theme', { backgroundColor: '#f4f4f4', textStyle: { color: '#333' } }); const ThemedChart: React.FC = () => { const [theme, setTheme] = useState('light_theme'); const option = { title: { text: 'Themed Waterfall Chart' }, tooltip: { trigger: 'axis' }, xAxis: { type: 'category', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] }, yAxis: { type: 'value' }, series: [{ name: 'Income', type: 'bar', stack: 'Total', data: [900, 345, 393, 500, 400, 600] }, { name: 'Expense', type: 'bar', stack: 'Total', data: [-200, -150, -100, -250, -180, -220] }] }; return ( <> ); }; export default ThemedChart; ``` -------------------------------- ### ReactECharts Component Props Source: https://github.com/hustcc/echarts-for-react/blob/master/README.md Configuration properties for the ReactECharts component to control chart rendering, themes, and behavior. ```APIDOC ## ReactECharts Component Props ### Description Properties used to configure the ReactECharts component instance. ### Parameters - **option** (object) - Required - The ECharts configuration object. - **notMerge** (object) - Optional - If true, prevents merging of data during setOption. - **replaceMerge** (string | string[]) - Optional - Specifies which components to replace during merge. - **lazyUpdate** (object) - Optional - If true, performs lazy updates for data. - **style** (object) - Optional - CSS style object for the chart container (default: {height: '300px'}). - **className** (string) - Optional - CSS class name for the chart container. - **theme** (string) - Optional - The theme name registered via echarts.registerTheme. - **onChartReady** (function) - Optional - Callback triggered when the chart is initialized, receiving the echarts instance. - **loadingOption** (object) - Optional - Configuration for the loading mask. - **showLoading** (bool) - Optional - If true, displays a loading mask. - **onEvents** (object) - Optional - Map of event names to handler functions. - **opts** (object) - Optional - Options passed to echarts.init (e.g., renderer: 'svg'). - **autoResize** (boolean) - Optional - Whether to automatically resize the chart on window resize (default: true). ``` -------------------------------- ### Interactive Pie Chart with Event Handling Source: https://context7.com/hustcc/echarts-for-react/llms.txt Shows how to handle ECharts events like 'click' and 'legendselectchanged' using the `onEvents` prop in ReactECharts. Event handlers receive parameters and the ECharts instance, allowing for dynamic chart interactions and state updates in the React component. ```tsx import React, { useState } from 'react'; import ReactECharts from 'echarts-for-react'; const InteractivePieChart: React.FC = () => { const [clickedItem, setClickedItem] = useState(null); const option = { title: { text: 'Traffic Sources', left: 'center' }, tooltip: { trigger: 'item', formatter: '{a}
{b}: {c} ({d}%)' }, legend: { orient: 'vertical', left: 'left', data: ['Direct', 'Email', 'Affiliate', 'Video', 'Search'] }, series: [{ name: 'Traffic Source', type: 'pie', radius: '55%', center: ['50%', '60%'], data: [ { value: 335, name: 'Direct' }, { value: 310, name: 'Email' }, { value: 234, name: 'Affiliate' }, { value: 135, name: 'Video' }, { value: 1548, name: 'Search' } ] }] }; function onChartReady(echarts) { console.log('Chart is ready:', echarts); } function onChartClick(params, echarts) { console.log('Clicked:', params); setClickedItem(params.name); } function onLegendSelectChanged(params, echarts) { console.log('Legend selection changed:', params.selected); } return ( <> {clickedItem &&
Last clicked: {clickedItem}
} ); }; export default InteractivePieChart; ```