Search code examples
reactjschart.jsreact-chartjs-2

How to use HTML for labels in react-chartjs?


I have the following code:

const historicDate = ['<span>${day}<br/>${time}</span>', /* many more... */]
<Line
  options={{
    responsive: true,
    plugins: {
      legend: {
        position: 'top' as const
      }
    }
  }}
  data={{
    labels: historicDate,
    datasets: [
      {
        label: 'Temperature',
        data: [30, 31, /* many more... */],
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.5)'
      }
    ]
  }}
/>

What I want to achieve is to display the historicDate array elements as html, but it is being displayed as a string.

Btw, I'm using:

  • chart.js: v4.1.1
  • react-chartjs-2: v5.1.0

Solution

  • To change the behavior of the x axis, I had to use the scales option. As follows:

    <Line
      options={{
        responsive: true,
        plugins: {
          legend: {
            position: 'top' as const
          }
        },
        scales: {
          x: {
            ticks: {
              callback: (value, index) => historicDate[index].split(',')
            }
          }
        }
      }}
      data={{
        labels: historicDate,
        datasets: [
          {
            label: 'Temperatura',
            data: historicTemperature,
            borderColor: 'rgb(255, 99, 132)',
            backgroundColor: 'rgba(255, 99, 132, 0.5)'
          }
        ]
      }}
    />