0
# Event Handling
1
2
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.
3
4
## Capabilities
5
6
### Get Dataset at Event
7
8
Gets dataset information from a mouse click event, useful for determining which dataset was clicked.
9
10
```typescript { .api }
11
/**
12
* Get dataset from mouse click event
13
* @param chart - Chart.js instance (accessible via ref)
14
* @param event - Mouse click event from React onClick handler
15
* @returns Array of InteractionItem objects representing the clicked dataset
16
*/
17
function getDatasetAtEvent(
18
chart: Chart,
19
event: MouseEvent<HTMLCanvasElement>
20
): InteractionItem[];
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import React, { useRef } from "react";
27
import { Bar, getDatasetAtEvent } from "react-chartjs-2";
28
import type { Chart as ChartJS } from "chart.js";
29
30
function InteractiveChart() {
31
const chartRef = useRef<ChartJS>(null);
32
33
const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
34
if (chartRef.current) {
35
const elements = getDatasetAtEvent(chartRef.current, event);
36
if (elements.length > 0) {
37
const datasetIndex = elements[0].datasetIndex;
38
console.log('Clicked dataset:', datasetIndex);
39
}
40
}
41
};
42
43
const data = {
44
labels: ['A', 'B', 'C'],
45
datasets: [
46
{
47
label: 'Dataset 1',
48
data: [1, 2, 3],
49
backgroundColor: 'rgba(255, 99, 132, 0.5)',
50
},
51
{
52
label: 'Dataset 2',
53
data: [2, 3, 4],
54
backgroundColor: 'rgba(54, 162, 235, 0.5)',
55
},
56
],
57
};
58
59
return (
60
<Bar
61
ref={chartRef}
62
data={data}
63
onClick={handleClick}
64
/>
65
);
66
}
67
```
68
69
### Get Element at Event
70
71
Gets the single nearest chart element from a mouse click event, useful for getting specific data points.
72
73
```typescript { .api }
74
/**
75
* Get single dataset element from mouse click event
76
* @param chart - Chart.js instance (accessible via ref)
77
* @param event - Mouse click event from React onClick handler
78
* @returns Array of InteractionItem objects (typically one element) representing the clicked data point
79
*/
80
function getElementAtEvent(
81
chart: Chart,
82
event: MouseEvent<HTMLCanvasElement>
83
): InteractionItem[];
84
```
85
86
**Usage Examples:**
87
88
```typescript
89
import React, { useRef } from "react";
90
import { Line, getElementAtEvent } from "react-chartjs-2";
91
import type { Chart as ChartJS } from "chart.js";
92
93
function ClickableLineChart() {
94
const chartRef = useRef<ChartJS>(null);
95
96
const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
97
if (chartRef.current) {
98
const elements = getElementAtEvent(chartRef.current, event);
99
if (elements.length > 0) {
100
const { datasetIndex, index } = elements[0];
101
const datasetLabel = chartRef.current.data.datasets[datasetIndex].label;
102
const value = chartRef.current.data.datasets[datasetIndex].data[index];
103
const label = chartRef.current.data.labels?.[index];
104
105
console.log(`Clicked: ${datasetLabel} - ${label}: ${value}`);
106
}
107
}
108
};
109
110
const data = {
111
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
112
datasets: [{
113
label: 'Sales',
114
data: [65, 59, 80, 81, 56],
115
borderColor: 'rgb(75, 192, 192)',
116
}],
117
};
118
119
return (
120
<Line
121
ref={chartRef}
122
data={data}
123
onClick={handleClick}
124
/>
125
);
126
}
127
```
128
129
### Get Elements at Event
130
131
Gets all chart elements at the clicked index position across all datasets, useful for multi-dataset comparisons.
132
133
```typescript { .api }
134
/**
135
* Get all dataset elements from mouse click event
136
* @param chart - Chart.js instance (accessible via ref)
137
* @param event - Mouse click event from React onClick handler
138
* @returns Array of InteractionItem objects representing all data points at the clicked index
139
*/
140
function getElementsAtEvent(
141
chart: Chart,
142
event: MouseEvent<HTMLCanvasElement>
143
): InteractionItem[];
144
```
145
146
**Usage Examples:**
147
148
```typescript
149
import React, { useRef } from "react";
150
import { Bar, getElementsAtEvent } from "react-chartjs-2";
151
import type { Chart as ChartJS } from "chart.js";
152
153
function MultiDatasetChart() {
154
const chartRef = useRef<ChartJS>(null);
155
156
const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
157
if (chartRef.current) {
158
const elements = getElementsAtEvent(chartRef.current, event);
159
if (elements.length > 0) {
160
const index = elements[0].index;
161
const label = chartRef.current.data.labels?.[index];
162
163
console.log(`Clicked label: ${label}`);
164
elements.forEach((element) => {
165
const datasetLabel = chartRef.current!.data.datasets[element.datasetIndex].label;
166
const value = chartRef.current!.data.datasets[element.datasetIndex].data[element.index];
167
console.log(` ${datasetLabel}: ${value}`);
168
});
169
}
170
}
171
};
172
173
const data = {
174
labels: ['Q1', 'Q2', 'Q3', 'Q4'],
175
datasets: [
176
{
177
label: '2022',
178
data: [10, 20, 30, 40],
179
backgroundColor: 'rgba(255, 99, 132, 0.5)',
180
},
181
{
182
label: '2023',
183
data: [15, 25, 35, 45],
184
backgroundColor: 'rgba(54, 162, 235, 0.5)',
185
},
186
],
187
};
188
189
return (
190
<Bar
191
ref={chartRef}
192
data={data}
193
onClick={handleClick}
194
/>
195
);
196
}
197
```
198
199
## Event Handler Setup
200
201
To use these event utilities, you need:
202
203
1. A ref to the chart component to access the Chart.js instance
204
2. An event handler attached to the chart component
205
3. The event utility function to extract the relevant data
206
207
```typescript
208
import React, { useRef } from "react";
209
import { Chart, getElementAtEvent } from "react-chartjs-2";
210
import type { Chart as ChartJS } from "chart.js";
211
212
function ChartWithEvents() {
213
const chartRef = useRef<ChartJS>(null);
214
215
const handleClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
216
if (chartRef.current) {
217
const elements = getElementAtEvent(chartRef.current, event);
218
// Handle the clicked elements...
219
}
220
};
221
222
const handleHover = (event: React.MouseEvent<HTMLCanvasElement>) => {
223
if (chartRef.current) {
224
const elements = getElementAtEvent(chartRef.current, event);
225
// Handle the hovered elements...
226
}
227
};
228
229
return (
230
<Chart
231
ref={chartRef}
232
type="line"
233
data={data}
234
onClick={handleClick}
235
onMouseMove={handleHover}
236
/>
237
);
238
}
239
```
240
241
## Types
242
243
```typescript { .api }
244
import type { MouseEvent } from 'react';
245
import type { Chart, InteractionItem } from 'chart.js';
246
247
// InteractionItem represents a chart element (data point, dataset, etc.)
248
interface InteractionItem {
249
/** Index of the dataset */
250
datasetIndex: number;
251
/** Index of the data point within the dataset */
252
index: number;
253
/** The chart element instance */
254
element: Element;
255
}
256
257
// Chart instance from Chart.js
258
interface Chart {
259
data: ChartData;
260
options: ChartOptions;
261
getElementsAtEventForMode(
262
event: Event,
263
mode: string,
264
options: { intersect: boolean },
265
useFinalPosition: boolean
266
): InteractionItem[];
267
}
268
```
269
270
## Common Use Cases
271
272
### Click to Show Details
273
274
```typescript
275
const handleDataPointClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
276
if (chartRef.current) {
277
const elements = getElementAtEvent(chartRef.current, event);
278
if (elements.length > 0) {
279
const { datasetIndex, index } = elements[0];
280
const dataset = chartRef.current.data.datasets[datasetIndex];
281
const value = dataset.data[index];
282
const label = chartRef.current.data.labels?.[index];
283
284
// Show modal, tooltip, or navigate to detail page
285
showDetailModal({ label, value, dataset: dataset.label });
286
}
287
}
288
};
289
```
290
291
### Multi-Dataset Comparison
292
293
```typescript
294
const handleColumnClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
295
if (chartRef.current) {
296
const elements = getElementsAtEvent(chartRef.current, event);
297
if (elements.length > 0) {
298
const index = elements[0].index;
299
const comparisons = elements.map(element => ({
300
dataset: chartRef.current!.data.datasets[element.datasetIndex].label,
301
value: chartRef.current!.data.datasets[element.datasetIndex].data[element.index]
302
}));
303
304
showComparisonView(comparisons);
305
}
306
}
307
};
308
```
309
310
### Dataset Toggle
311
312
```typescript
313
const handleDatasetClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
314
if (chartRef.current) {
315
const elements = getDatasetAtEvent(chartRef.current, event);
316
if (elements.length > 0) {
317
const datasetIndex = elements[0].datasetIndex;
318
319
// Toggle dataset visibility
320
chartRef.current.setDatasetVisibility(
321
datasetIndex,
322
!chartRef.current.isDatasetVisible(datasetIndex)
323
);
324
chartRef.current.update();
325
}
326
}
327
};
328
```