DEV Community

Aaron King
Aaron King

Posted on

Building Interactive Charts with ECharts for React

ECharts for React is a React wrapper for Apache ECharts, a powerful charting library. It provides a React-friendly API for creating interactive, responsive charts with extensive customization options. This guide walks through setting up and creating charts using ECharts for React, from installation to a working implementation.

Prerequisites

Before you begin, make sure you have:

  • Node.js version 14.0 or higher installed
  • npm, yarn, or pnpm package manager
  • A React project (version 16.8 or higher) or create-react-app setup
  • Basic knowledge of React hooks (useState, useEffect, useRef)
  • Familiarity with JavaScript/TypeScript

Installation

Install ECharts for React and ECharts core:

npm install echarts echarts-for-react
Enter fullscreen mode Exit fullscreen mode

Or with yarn:

yarn add echarts echarts-for-react
Enter fullscreen mode Exit fullscreen mode

Or with pnpm:

pnpm add echarts echarts-for-react
Enter fullscreen mode Exit fullscreen mode

After installation, your package.json should include:

{
  "dependencies": {
    "echarts": "^5.0.0",
    "echarts-for-react": "^3.0.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Project Setup

ECharts for React requires minimal setup. Import the component and you're ready to use it.

First Example / Basic Usage

Let's create a simple line chart. Create a new file src/ChartExample.jsx:

// src/ChartExample.jsx
import React from 'react';
import ReactECharts from 'echarts-for-react';

function ChartExample() {
  const option = {
    title: {
      text: 'Monthly Sales'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'Sales',
        type: 'line',
        data: [35, 28, 34, 32, 40, 32],
        smooth: true
      }
    ]
  };

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h2>Basic ECharts Example</h2>
      <ReactECharts option={option} style={{ height: '400px' }} />
    </div>
  );
}

export default ChartExample;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import ChartExample from './ChartExample';
import './App.css';

function App() {
  return (
    <div className="App">
      <ChartExample />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This creates a basic line chart with tooltips and smooth animations.

Understanding the Basics

ECharts for React uses an option-based configuration:

  • ReactECharts component: Main chart component
  • option object: Chart configuration
  • Chart types: Line, Bar, Pie, Scatter, etc.
  • Interactive features: Tooltip, zoom, brush, etc.
  • Responsive: Automatic responsive behavior

Key concepts:

  • Option object: Configure chart through an option prop
  • Chart structure: title, tooltip, xAxis, yAxis, series
  • Series array: Define data series
  • Styling: Customize colors, themes, and styles
  • Events: Handle chart events with callbacks

Here's an example with multiple chart types:

// src/MultipleChartsExample.jsx
import React from 'react';
import ReactECharts from 'echarts-for-react';

function MultipleChartsExample() {
  const lineOption = {
    title: { text: 'Line Chart' },
    xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
    yAxis: { type: 'value' },
    series: [{ type: 'line', data: [120, 132, 101, 134, 90] }]
  };

  const barOption = {
    title: { text: 'Bar Chart' },
    xAxis: { type: 'category', data: ['Product A', 'Product B', 'Product C'] },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: [120, 200, 150] }]
  };

  const pieOption = {
    title: { text: 'Pie Chart' },
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
        { value: 580, name: 'Email' }
      ]
    }]
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <h2>Multiple Charts Example</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '40px' }}>
        <ReactECharts option={lineOption} style={{ height: '300px' }} />
        <ReactECharts option={barOption} style={{ height: '300px' }} />
        <ReactECharts option={pieOption} style={{ height: '300px' }} />
      </div>
    </div>
  );
}

export default MultipleChartsExample;
Enter fullscreen mode Exit fullscreen mode

Practical Example / Building Something Real

Let's build a comprehensive dashboard with multiple charts:

// src/DashboardCharts.jsx
import React, { useState } from 'react';
import ReactECharts from 'echarts-for-react';

function DashboardCharts() {
  const [selectedPeriod, setSelectedPeriod] = useState('monthly');

  const salesData = {
    monthly: {
      xAxis: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
      sales: [35, 28, 34, 32, 40, 32],
      target: [40, 35, 38, 36, 42, 38]
    },
    quarterly: {
      xAxis: ['Q1', 'Q2', 'Q3', 'Q4'],
      sales: [97, 106, 112, 120],
      target: [113, 116, 120, 125]
    }
  };

  const currentData = salesData[selectedPeriod];

  const salesOption = {
    title: {
      text: 'Sales Performance',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['Sales', 'Target'],
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: currentData.xAxis
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'Sales',
        type: 'line',
        data: currentData.sales,
        smooth: true,
        itemStyle: { color: '#5470c6' }
      },
      {
        name: 'Target',
        type: 'line',
        data: currentData.target,
        smooth: true,
        itemStyle: { color: '#91cc75' }
      }
    ]
  };

  const revenueOption = {
    title: {
      text: 'Revenue by Category',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: [
        { value: 1048, name: 'Product A' },
        { value: 735, name: 'Product B' },
        { value: 580, name: 'Product C' },
        { value: 484, name: 'Product D' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  };

  const barOption = {
    title: {
      text: 'Monthly Comparison',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: [35, 28, 34, 32, 40, 32],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      }
    }]
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <h1>Sales Dashboard</h1>
      <div style={{ marginBottom: '20px', textAlign: 'center' }}>
        <button
          onClick={() => setSelectedPeriod('monthly')}
          style={{
            padding: '8px 16px',
            margin: '0 5px',
            backgroundColor: selectedPeriod === 'monthly' ? '#007bff' : '#6c757d',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          Monthly
        </button>
        <button
          onClick={() => setSelectedPeriod('quarterly')}
          style={{
            padding: '8px 16px',
            margin: '0 5px',
            backgroundColor: selectedPeriod === 'quarterly' ? '#007bff' : '#6c757d',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          Quarterly
        </button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '40px' }}>
        <ReactECharts option={salesOption} style={{ height: '400px' }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
          <ReactECharts option={revenueOption} style={{ height: '400px' }} />
          <ReactECharts option={barOption} style={{ height: '400px' }} />
        </div>
      </div>
    </div>
  );
}

export default DashboardCharts;
Enter fullscreen mode Exit fullscreen mode

Now create an interactive chart with events:

// src/InteractiveChart.jsx
import React, { useState } from 'react';
import ReactECharts from 'echarts-for-react';

function InteractiveChart() {
  const [selectedData, setSelectedData] = useState(null);

  const option = {
    title: {
      text: 'Interactive Sales Chart',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['Sales', 'Profit'],
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
    },
    yAxis: [
      {
        type: 'value',
        name: 'Sales',
        position: 'left'
      },
      {
        type: 'value',
        name: 'Profit',
        position: 'right'
      }
    ],
    series: [
      {
        name: 'Sales',
        type: 'bar',
        data: [35, 28, 34, 32, 40, 32],
        yAxisIndex: 0
      },
      {
        name: 'Profit',
        type: 'line',
        data: [10, 8, 12, 9, 15, 11],
        yAxisIndex: 1,
        smooth: true
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        start: 0,
        end: 100
      }
    ]
  };

  const onChartReady = (echarts) => {
    console.log('Chart is ready', echarts);
  };

  const onEvents = {
    click: (params) => {
      console.log('Chart clicked', params);
      setSelectedData(params.data);
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '900px', margin: '0 auto' }}>
      <h2>Interactive Chart</h2>
      {selectedData && (
        <div style={{
          padding: '10px',
          backgroundColor: '#f8f9fa',
          borderRadius: '4px',
          marginBottom: '20px'
        }}>
          Selected: {JSON.stringify(selectedData)}
        </div>
      )}
      <ReactECharts
        option={option}
        style={{ height: '500px' }}
        onChartReady={onChartReady}
        onEvents={onEvents}
      />
    </div>
  );
}

export default InteractiveChart;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import DashboardCharts from './DashboardCharts';
import InteractiveChart from './InteractiveChart';
import './App.css';

function App() {
  return (
    <div className="App">
      <DashboardCharts />
      <InteractiveChart />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This example demonstrates:

  • Multiple chart types
  • Dashboard layout
  • Interactive features
  • Event handling
  • Dynamic data updates
  • Custom styling

Common Issues / Troubleshooting

  1. Chart not displaying: Make sure you've installed both echarts and echarts-for-react. The chart requires the ECharts core library.

  2. Option not working: Check that the option object follows ECharts configuration format. Refer to ECharts documentation for correct option structure.

  3. Responsive issues: ECharts handles responsiveness automatically. If charts aren't resizing, ensure the container has proper dimensions.

  4. Events not firing: Use the onEvents prop to attach event handlers. Make sure event names match ECharts event names.

  5. Styling issues: Customize colors and styles in the option object. Use itemStyle for series styling and textStyle for text styling.

  6. Performance: For large datasets, consider using data sampling or lazy loading. ECharts handles large datasets well, but optimization may be needed.

Next Steps

Now that you have an understanding of ECharts for React:

  • Explore all available chart types
  • Learn about advanced configurations
  • Implement real-time data updates
  • Add custom tooltips and formatters
  • Create 3D charts and maps
  • Learn about other chart libraries (recharts, chart.js)
  • Check the official repository: https://github.com/hustcc/echarts-for-react

Summary

You've successfully set up ECharts for React in your React application and created interactive charts, dashboards, and data visualizations. ECharts for React provides a powerful solution for creating professional charts with extensive customization and interactive features.

SEO Keywords

echarts-for-react
React ECharts
echarts-for-react tutorial
React Apache ECharts
echarts-for-react installation
React interactive charts
echarts-for-react example
React data visualization
echarts-for-react setup
React chart library
echarts-for-react customization
React ECharts dashboard
echarts-for-react events
React chart component
echarts-for-react getting started

Top comments (0)