Blog>
Snippets

Creating a Responsive Bar Chart

Provide code example for creating a responsive bar chart using TanStack React Charts that adjusts to the screen size and demonstrates basic interaction through a tooltip feature.
import { Chart } from 'react-chartjs-2';
import { CategoryScale, LinearScale, BarElement, Title, Tooltip, Chart as ChartJS } from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip);
First, import necessary components from 'react-chartjs-2' and 'chart.js', and register the chart components.
const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [
    {
      label: 'Monthly Sales',
      data: [65, 59, 80, 81, 56, 55],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }
  ]
};
Define the dataset for the bar chart. It includes labels for the x-axis and dataset for the bars including colors for both fill and border.
const options = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    y: {
      beginAtZero: true
    }
  },
  plugins: {
    tooltip: {
      enabled: true
    }
  }
};
Set up chart options including making the chart responsive, starting the y-axis from zero, and enabling tooltips for interaction.
const BarChart = () => (
  <div style={{ height: '400px' }}>
    <Chart type='bar' data={data} options={options} />
  </div>
);
Create the BarChart component with a fixed height and render the Chart component from 'react-chartjs-2' passing the data and options as props.
export default BarChart;
Export the BarChart component so it can be used in other parts of the application.