I have a created a bar chart using chart js. The chart loads fine but while trying to create a custom tooltip I am encountering the following which I believe is stopping the tooltip from being created:
Invalid usage of "getElementById". DOM query at the document level is forbidden.
This is what I have for my chart config:
tooltips: {
enabled: false,
callbacks: {
label: function (tooltipItem, data) {
let items = [];
data.forEach((item) => {
items.push(item);
});
return `Item: ${items}`;
},
},
custom: function (tooltip) {
// Tooltip Element
// having trouble here since we can't access ids in LWC, only classes
// lws does not allow access to the document object
let tooltipEl = document.getElementById('chartjs-tooltip');
console.log('>element: ', tooltipEl);
// Create element on first render
if (!tooltipEl) {
//tooltipEl = this.template.createElement('div');
//tooltipEl = document.createElement('div');
//tooltipEl.className = 'chartjs-tooltip';
//tooltipEl.innerHTML = '<table></table>';
//document.body.appendChild(tooltipEl);
//this.template.appendChild(chartjs-tooltip)
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltip.body) {
const titleLines = tooltip.title || [];
const bodyLines = tooltip.body.map(getBody);
console.log('>>bodyLines: ', bodyLines);
let innerHtml = '<thead>';
titleLines.forEach(function (title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
console.log('titleLines:', titleLines);
}
},
What I've tried based on this documentation: https://github.com/salesforce/eslint-plugin-lwc/blob/v1.6.2/docs/rules/no-document-query.md
let tooltipEl = self.template.querySelector('.chartjs-tooltip');
I also tried adding a div to the html:
<div id="barChart" class={chartClass}>
<div id="chartjs-tooltip">
<table></table>
</div>
<canvas
class="bar-chart"
lwc:dom="manual"
></canvas>
</div>
Any help or insight would be greatly appreciated.