# Event Handling

Utility functions for handling user interactions with charts, extracting chart data from mouse events. These functions help you implement interactive chart features like click handlers and hover effects.

## Capabilities

### Get Dataset at Event

Gets dataset information from a mouse click event, useful for determining which dataset was clicked.

```typescript { .api }
/**
 * Get dataset from mouse click event
 * @param chart - Chart.js instance (accessible via ref)
 * @param event - Mouse click event from React onClick handler
 * @returns Array of InteractionItem objects representing the clicked dataset
 */
function getDatasetAtEvent(
  chart: Chart,
  event: MouseEvent<HTMLCanvasElement>
): InteractionItem[];
```

**Usage Examples:**

```typescript
import React, { useRef } from "react";
import { Bar, getDatasetAtEvent } from "react-chartjs-2";
import type { Chart as ChartJS } from "chart.js";

function InteractiveChart() {
  const chartRef = useRef<ChartJS>(null);

  const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      const elements = getDatasetAtEvent(chartRef.current, event);
      if (elements.length > 0) {
        const datasetIndex = elements[0].datasetIndex;
        console.log('Clicked dataset:', datasetIndex);
      }
    }
  };

  const data = {
    labels: ['A', 'B', 'C'],
    datasets: [
      {
        label: 'Dataset 1',
        data: [1, 2, 3],
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
      },
      {
        label: 'Dataset 2', 
        data: [2, 3, 4],
        backgroundColor: 'rgba(54, 162, 235, 0.5)',
      },
    ],
  };

  return (
    <Bar
      ref={chartRef}
      data={data}
      onClick={handleClick}
    />
  );
}
```

### Get Element at Event

Gets the single nearest chart element from a mouse click event, useful for getting specific data points.

```typescript { .api }
/**
 * Get single dataset element from mouse click event
 * @param chart - Chart.js instance (accessible via ref)
 * @param event - Mouse click event from React onClick handler
 * @returns Array of InteractionItem objects (typically one element) representing the clicked data point
 */
function getElementAtEvent(
  chart: Chart,
  event: MouseEvent<HTMLCanvasElement>
): InteractionItem[];
```

**Usage Examples:**

```typescript
import React, { useRef } from "react";
import { Line, getElementAtEvent } from "react-chartjs-2";
import type { Chart as ChartJS } from "chart.js";

function ClickableLineChart() {
  const chartRef = useRef<ChartJS>(null);

  const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      const elements = getElementAtEvent(chartRef.current, event);
      if (elements.length > 0) {
        const { datasetIndex, index } = elements[0];
        const datasetLabel = chartRef.current.data.datasets[datasetIndex].label;
        const value = chartRef.current.data.datasets[datasetIndex].data[index];
        const label = chartRef.current.data.labels?.[index];
        
        console.log(`Clicked: ${datasetLabel} - ${label}: ${value}`);
      }
    }
  };

  const data = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [{
      label: 'Sales',
      data: [65, 59, 80, 81, 56],
      borderColor: 'rgb(75, 192, 192)',
    }],
  };

  return (
    <Line
      ref={chartRef}
      data={data}
      onClick={handleClick}
    />
  );
}
```

### Get Elements at Event

Gets all chart elements at the clicked index position across all datasets, useful for multi-dataset comparisons.

```typescript { .api }
/**
 * Get all dataset elements from mouse click event
 * @param chart - Chart.js instance (accessible via ref)
 * @param event - Mouse click event from React onClick handler
 * @returns Array of InteractionItem objects representing all data points at the clicked index
 */
function getElementsAtEvent(
  chart: Chart,
  event: MouseEvent<HTMLCanvasElement>
): InteractionItem[];
```

**Usage Examples:**

```typescript
import React, { useRef } from "react";
import { Bar, getElementsAtEvent } from "react-chartjs-2";
import type { Chart as ChartJS } from "chart.js";

function MultiDatasetChart() {
  const chartRef = useRef<ChartJS>(null);

  const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      const elements = getElementsAtEvent(chartRef.current, event);
      if (elements.length > 0) {
        const index = elements[0].index;
        const label = chartRef.current.data.labels?.[index];
        
        console.log(`Clicked label: ${label}`);
        elements.forEach((element) => {
          const datasetLabel = chartRef.current!.data.datasets[element.datasetIndex].label;
          const value = chartRef.current!.data.datasets[element.datasetIndex].data[element.index];
          console.log(`  ${datasetLabel}: ${value}`);
        });
      }
    }
  };

  const data = {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [
      {
        label: '2022',
        data: [10, 20, 30, 40],
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
      },
      {
        label: '2023',
        data: [15, 25, 35, 45],
        backgroundColor: 'rgba(54, 162, 235, 0.5)',
      },
    ],
  };

  return (
    <Bar
      ref={chartRef}
      data={data}
      onClick={handleClick}
    />
  );
}
```

## Event Handler Setup

To use these event utilities, you need:

1. A ref to the chart component to access the Chart.js instance
2. An event handler attached to the chart component
3. The event utility function to extract the relevant data

```typescript
import React, { useRef } from "react";
import { Chart, getElementAtEvent } from "react-chartjs-2";
import type { Chart as ChartJS } from "chart.js";

function ChartWithEvents() {
  const chartRef = useRef<ChartJS>(null);

  const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      const elements = getElementAtEvent(chartRef.current, event);
      // Handle the clicked elements...
    }
  };

  const handleHover = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (chartRef.current) {
      const elements = getElementAtEvent(chartRef.current, event);
      // Handle the hovered elements...
    }
  };

  return (
    <Chart
      ref={chartRef}
      type="line"
      data={data}
      onClick={handleClick}
      onMouseMove={handleHover}
    />
  );
}
```

## Types

```typescript { .api }
import type { MouseEvent } from 'react';
import type { Chart, InteractionItem } from 'chart.js';

// InteractionItem represents a chart element (data point, dataset, etc.)
interface InteractionItem {
  /** Index of the dataset */
  datasetIndex: number;
  /** Index of the data point within the dataset */
  index: number;
  /** The chart element instance */
  element: Element;
}

// Chart instance from Chart.js
interface Chart {
  data: ChartData;
  options: ChartOptions;
  getElementsAtEventForMode(
    event: Event,
    mode: string,
    options: { intersect: boolean },
    useFinalPosition: boolean
  ): InteractionItem[];
}
```

## Common Use Cases

### Click to Show Details

```typescript
const handleDataPointClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
  if (chartRef.current) {
    const elements = getElementAtEvent(chartRef.current, event);
    if (elements.length > 0) {
      const { datasetIndex, index } = elements[0];
      const dataset = chartRef.current.data.datasets[datasetIndex];
      const value = dataset.data[index];
      const label = chartRef.current.data.labels?.[index];
      
      // Show modal, tooltip, or navigate to detail page
      showDetailModal({ label, value, dataset: dataset.label });
    }
  }
};
```

### Multi-Dataset Comparison

```typescript
const handleColumnClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
  if (chartRef.current) {
    const elements = getElementsAtEvent(chartRef.current, event);
    if (elements.length > 0) {
      const index = elements[0].index;
      const comparisons = elements.map(element => ({
        dataset: chartRef.current!.data.datasets[element.datasetIndex].label,
        value: chartRef.current!.data.datasets[element.datasetIndex].data[element.index]
      }));
      
      showComparisonView(comparisons);
    }
  }
};
```

### Dataset Toggle

```typescript
const handleDatasetClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
  if (chartRef.current) {
    const elements = getDatasetAtEvent(chartRef.current, event);
    if (elements.length > 0) {
      const datasetIndex = elements[0].datasetIndex;
      
      // Toggle dataset visibility
      chartRef.current.setDatasetVisibility(
        datasetIndex,
        !chartRef.current.isDatasetVisible(datasetIndex)
      );
      chartRef.current.update();
    }
  }
};
```