Event Handling

Learn how to handle chart events and user interactions in react-echarts-library

Overview

React ECharts provides a powerful event system for handling user interactions. You can listen to mouse events, data events, and component-specific events.

Basic Event Handling

Use the onEvents prop to attach event handlers:

import { EChartsReact } from 'react-echarts-library';

function InteractiveChart() {
  const option = {
    xAxis: { type: 'category', data: ['A', 'B', 'C', 'D', 'E'] },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: [120, 200, 150, 80, 70] }]
  };

  const onEvents = {
    click: (params) => {
      console.log('Clicked:', params.name, params.value);
    }
  };

  return <EChartsReact option={option} onEvents={onEvents} />;
}

Event Parameters

Most event handlers receive a params object with these properties:

interface EventParams {
  // Component info
  componentType: string;    // 'series', 'xAxis', 'yAxis', etc.
  componentIndex: number;

  // Series info
  seriesType: string;       // 'line', 'bar', 'pie', etc.
  seriesIndex: number;
  seriesName: string;

  // Data info
  name: string;             // Category name
  dataIndex: number;        // Index in data array
  data: any;                // Original data item
  value: any;               // Data value

  // Visual info
  color: string;            // Item color

  // DOM event
  event: MouseEvent;
}

Mouse Events

Basic Mouse Events

const onEvents = {
  click: (params) => {
    console.log('Single click');
  },
  dblclick: (params) => {
    console.log('Double click');
  },
  mousedown: (params) => {
    console.log('Mouse down');
  },
  mouseup: (params) => {
    console.log('Mouse up');
  },
  mouseover: (params) => {
    console.log('Mouse enter');
  },
  mouseout: (params) => {
    console.log('Mouse leave');
  },
  contextmenu: (params) => {
    console.log('Right click');
    params.event.preventDefault();
  }
};

Global Mouse Events

const onEvents = {
  globalout: () => {
    console.log('Mouse left the chart area');
  }
};

Component Events

Legend Events

const onEvents = {
  legendselectchanged: (params) => {
    console.log('Legend changed:', params.name);
    console.log('Selected state:', params.selected);
  },
  legendselected: (params) => {
    console.log('Legend selected:', params.name);
  },
  legendunselected: (params) => {
    console.log('Legend unselected:', params.name);
  }
};

DataZoom Events

const onEvents = {
  datazoom: (params) => {
    console.log('DataZoom changed');
    console.log('Start:', params.start, 'End:', params.end);
  }
};

Brush Events

const onEvents = {
  brush: (params) => {
    console.log('Brush areas:', params.areas);
  },
  brushselected: (params) => {
    console.log('Selected data:', params.batch);
  }
};

Practical Examples

Click to Show Details

function ChartWithDetails() {
  const [selected, setSelected] = useState(null);

  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: ['Jan', 'Feb', 'Mar', 'Apr', 'May']
    },
    yAxis: { type: 'value' },
    series: [{
      type: 'bar',
      data: [
        { value: 120, details: 'January sales data' },
        { value: 200, details: 'February sales data' },
        { value: 150, details: 'March sales data' },
        { value: 80, details: 'April sales data' },
        { value: 70, details: 'May sales data' }
      ]
    }]
  };

  const onEvents = {
    click: (params) => {
      setSelected({
        name: params.name,
        value: params.value,
        details: params.data.details
      });
    }
  };

  return (
    <div>
      <EChartsReact option={option} onEvents={onEvents} style={{ height: 300 }} />
      {selected && (
        <div>
          <h3>{selected.name}</h3>
          <p>Value: {selected.value}</p>
          <p>{selected.details}</p>
        </div>
      )}
    </div>
  );
}

Highlight on Hover

function HighlightChart() {
  const chartRef = useRef(null);

  const onEvents = {
    mouseover: (params) => {
      chartRef.current?.getEchartsInstance()?.dispatchAction({
        type: 'highlight',
        seriesIndex: params.seriesIndex,
        dataIndex: params.dataIndex
      });
    },
    mouseout: (params) => {
      chartRef.current?.getEchartsInstance()?.dispatchAction({
        type: 'downplay',
        seriesIndex: params.seriesIndex,
        dataIndex: params.dataIndex
      });
    }
  };

  return (
    <EChartsReact
      ref={chartRef}
      option={option}
      onEvents={onEvents}
    />
  );
}

Linked Charts

function LinkedCharts() {
  const [highlightIndex, setHighlightIndex] = useState(-1);

  const onEvents = {
    mouseover: (params) => setHighlightIndex(params.dataIndex),
    mouseout: () => setHighlightIndex(-1)
  };

  const option1 = {
    xAxis: { type: 'category', data: ['A', 'B', 'C'] },
    yAxis: { type: 'value' },
    series: [{
      type: 'bar',
      data: [10, 20, 30],
      emphasis: { disabled: false }
    }]
  };

  const option2 = {
    xAxis: { type: 'category', data: ['A', 'B', 'C'] },
    yAxis: { type: 'value' },
    series: [{
      type: 'line',
      data: [30, 20, 10],
      emphasis: { disabled: false }
    }]
  };

  return (
    <div style={{ display: 'flex', gap: '1rem' }}>
      <EChartsReact
        option={option1}
        onEvents={onEvents}
        style={{ flex: 1, height: 300 }}
      />
      <EChartsReact
        option={option2}
        onEvents={onEvents}
        style={{ flex: 1, height: 300 }}
      />
    </div>
  );
}

Using Chart Instance

Access the ECharts instance for programmatic control:

function ChartWithControls() {
  const chartRef = useRef(null);

  const triggerHighlight = (index) => {
    const chart = chartRef.current?.getEchartsInstance();
    if (chart) {
      chart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: index
      });
    }
  };

  const clearHighlight = () => {
    const chart = chartRef.current?.getEchartsInstance();
    if (chart) {
      chart.dispatchAction({
        type: 'downplay',
        seriesIndex: 0
      });
    }
  };

  return (
    <div>
      <EChartsReact ref={chartRef} option={option} />
      <div>
        <button onClick={() => triggerHighlight(0)}>Highlight A</button>
        <button onClick={() => triggerHighlight(1)}>Highlight B</button>
        <button onClick={clearHighlight}>Clear</button>
      </div>
    </div>
  );
}

Tips

  1. Event names are lowercase - Use click, not Click or onClick
  2. Check params.componentType - Filter events by component type
  3. Use event.preventDefault() - Prevent default browser behavior
  4. Clean up - Event handlers are automatically cleaned up on unmount