简体   繁体   中英

ChartJS 3.7.1 tooltip callback, get label value for the next index

I'm currently migrating from 2.9.3 to 3.7.1 and I'm having trouble with migrating a callback function from the options object.

Former location: options.tooltips.callbacks.title
Migrated location: options.plugins.tooltip.callbacks.title

Former function (simplified):

function (tooltipItems, data) {
    var tooltipItem = tooltipItems[0];
    var currentLabel = data.labels[tooltipItem.index];
    var nextLabel = data.labels[tooltipItem.index +1];
    return currentLabel + ' - ' + nextLabel;
}

Migrated function:

function (tooltipItems) {
    var tooltipItem = tooltipItems[0];
    var currentLabel = tooltipItem.label;
    var nextLabel = ? // how to get nextLabel?
    return currentLabel + ' - ' + nextLabel;
}

tooltipItem.dataset has a label array but that appears empty when i console.log(tooltipItems)

You get access to the chart object and have the data index so you can just get the correct label from the labels array like so:

title: (items) => {
  const item = items[0];
  const {
    chart
  } = item;
  const nextLabel = chart.data.labels[item.dataIndex + 1] || '';
  return `${item.label}, next label: ${nextLabel}`;
}

 const options = { type: 'line', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderColor: 'orange' }, { label: '# of Points', data: [7, 11, 5, 8, 3, 7], borderColor: 'pink' } ] }, options: { plugins: { tooltip: { callbacks: { title: (items) => { const item = items[0]; const { chart } = item; const nextLabel = chart.data.labels[item.dataIndex + 1] || ''; return `${item.label}, next label: ${nextLabel}`; } } } } } } const ctx = document.getElementById('chartJSContainer').getContext('2d'); new Chart(ctx, options);
 <body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM