Events
Listen to Chart Events
react-google-charts
also supports event listeners, enabling you to trigger callbacks when chart interactions occur. For example, you can log the selected chart items on a ScatterChart using the select
event.
import { Chart } from "react-google-charts";
const chartEvents = [
{
eventName: "select",
callback({ chartWrapper }) {
console.log("Selected ", chartWrapper.getChart().getSelection());
},
},
{
eventName: "ready",
callback({ chartWrapper }) {
console.log("Chart ready. ", chartWrapper.getChart());
},
},
{
eventName: "error",
callback(args) {
console.log("Chart errored. ", args);
},
},
];
const data = [
["age", "weight"],
[8, 12],
[4, 5.5],
[11, 14],
[4, 5],
[3, 3.5],
[6.5, 7],
];
const options = {
title: "Age vs. Weight Comparison",
hAxis: { title: "Age", viewWindow: { min: 0, max: 15 } },
vAxis: { title: "Weight", viewWindow: { min: 0, max: 15 } },
legend: "none",
};
<Chart
chartType="ScatterChart"
data={data}
options={options}
chartEvents={chartEvents}
/>;
Event Highlights
eventName
: Specifies the event to listen for (e.g.,"select" | "error" | "ready"
).callback
: The function that gets triggered when the event occurs, providing access to the chart instance and event data.