[Chartjs]-Responsive legend font size in react-chartjs 2

2👍

You can set your fontSize object as a ternery operator that checks the widts (or something else) to see if you are on a mobile device and give back the right fontSize according to it

If you want to update it real time because screen sizes change you can do that by mutating the chart options itself in a resizeEvent listner

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      labels: {
        fontSize: window.innerWidth > 350 ? 20 : 10
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);

window.addEventListener('resize', () => {
  if (window.innerWidth < 350) {
    chart.options.legend.labels.fontSize = 10;
  } else {
    chart.options.legend.labels.fontSize = 20
  }
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

1👍

Here is the way to have a responsive legend font size (also explained here)

options: {
        plugins: {
            legend: {
                labels: {
                    // This more specific font property overrides the global property
                    font: {
                        size: 14
                    }
                }
            }
        }
    }

Leave a comment