Chartjs-React-chart-js-2 keep bar width no matter what the number of bar is

0👍

You can wrap your chart in a div and then set the height of the div according to the height it needs to be like so:

let DATA_COUNT = Math.max(1, Math.round(Math.random() * 10));
const LABELS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
const data = {
  labels: [],
  datasets: [{
    backgroundColor: "green",
    data: []
  }]
};

const chart = new Chart("chart", {
  type: "bar",
  data,
  options: {
    responsive: true,
    maintainAspectRatio: false,
    indexAxis: "y",
    plugins: {
      legend: false
    },
    layout: {
      padding: {
        top: 10
      }
    }
  }
});

const div = document.getElementById("container");

function update() {
  DATA_COUNT = Math.max(1, Math.round(Math.random() * 10));
  data.labels = [];
  data.datasets[0].data = [];
  for (let i = 0; i < DATA_COUNT; i++) {
    data.labels.push(LABELS[i]);
    data.datasets[0].data.push(i + 1);
  }
  chart.update();
  const scale = chart.scales.x.height;
  div.style.height = 10 + scale + DATA_COUNT * 20 + "px";
}

update();

document.getElementById("update").addEventListener("click", update);
.chart {
  width: 512px;
  height: 256px;
  border: 1px solid black;
  border-radius: 4px;
  margin: 4px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<button id="update">Update</Button>
<div class="chart" id="container"><canvas id="chart"></canvas></div>

Comming from this github issue: https://github.com/chartjs/Chart.js/issues/5409

Leave a comment