Skip to content

Instantly share code, notes, and snippets.

@denisos
Created November 4, 2022 16:53
Show Gist options
  • Save denisos/5b22a3dba0fec7cc58f6f566e9d40672 to your computer and use it in GitHub Desktop.
Save denisos/5b22a3dba0fec7cc58f6f566e9d40672 to your computer and use it in GitHub Desktop.
using react-chartjs to show bar chart and add onClick handler
import React, { useEffect, useState, useRef } from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Bar, getElementAtEvent } from 'react-chartjs-2';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
import styles from './index.module.scss';
// chart js config
const chartOptions = {
// responsive: true,
maintainAspectRatio:false,
plugins: {
legend: {
position: 'top' as const,
},
title: {
display: true,
text: 'Sales figures',
},
},
};
const labels = ['east', 'west', 'north', 'south'];
const defaultChartData = {
labels,
datasets: [
{
label: '',
data: [5,6,22,12],
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
}
// end chart js config
export const RegionalSales = () => {
const [ chartData, setChartData ] = useState(defaultChartData);
const chartRef = useRef();
const chartOnClick = (event: any) => {
const elementClicked = getElementAtEvent(chartRef.current, event);
if (elementClicked?.length > 0) {
const index = elementClicked[0].index;
// set chartData by filter salesData based on bar clicked
// the index matches the bar column 0,1,2 etc
// instead of if else, could do a map lookup by index
if (index == 0) {
// do something e.g. filter a table to just show bar chart column 1 data
} else if (index == 1) {
// do something e.g. filter a table to just show bar chart column 2 data
} else {
// etc
}
}
}
return (
<main className={styles.main}>
<div className={styles.chartContainer}>
<Bar options={chartOptions} data={chartData} ref={chartRef} onClick={chartOnClick} />
</div>
</main>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment