I am using chartjs-2 in react functional component (please find the code here: https://codesandbox.io/s/elastic-brook-okkce?file=/src/Dashboard.jsx)
I have rendered 4 bars here and I want to have a specific handler function defined for onClick event on each bar. Like there are 4 types in the bar labels and on clicking on each bar I want to display something specific to the type of the bar clicked. How to implement this?
function Dashboard(props) {
const classes = useStyles();
const [data, setdata] = React.useState({
labels: ["type1", "type2", "type3", "type4"],
datasets: [
{
label: "text that comes on hover",
backgroundColor: [
//................................................colors of the bars............
"#3e95cd",
"#8e5ea2",
"#3cba9f",
"#e8c3b9",
"#c45850"
],
barThickness: 80,
data: [50, 100, 75, 20, 0] //......................values for each bar...........
}
]
});
const getChartData = canvas => {
return data;
};
return (
<React.Fragment>
<div
className={classes.chart}
style={{ position: "relative", width: 900, height: 450 }}
>
<Bar
options={{
responsive: true,
maintainAspectRatio: true,
legend: { display: false },
title: {
display: true,
text: "Title for the graph"
}
}}
data={getChartData}
/>
</div>
</React.Fragment>
);
}
export default Dashboard;
You can use onElementsClick
. Please check the below code:
<Bar
options={{
responsive: true,
maintainAspectRatio: true,
legend: {display: false},
title: {
display: true,
text: "Title for the graph"
}
}}
onElementsClick={(e) => {
console.log(e, 'e')
}}
data={getChartData}
/>