I was trying to get jQuery Datatables work in my LWC. I have tried this: LWC is it Possible to Load the JQuery Plugin Datatables in a Lightning Web Component?
But I was not able to get it work.
Everything went well until this line of code:
let dataTable = $(table).DataTable();
It actually removed the <table>
element from the page.
Can anybody help me here? Thanks in advance!!!
Code here:
HTML
<template>
<table lwc:dom="manual" class="example-table display" style="width:100%"></table>
</template>
JS
import { loadStyle, loadScript } from 'lightning/platformResourceLoader';
import jQuery from '@salesforce/resourceUrl/jQuery';
import DATATABLES_JS from '@salesforce/resourceUrl/DataTables_js';
import DATATABLES_CSS from '@salesforce/resourceUrl/DataTables_css';
renderedCallback() {
if(firstTimeRender) {
loadScript(this, jQuery).then(() => {
console.log('Loaded JQUERY');
loadStyle(this, DATATABLES_CSS).then(() => {
console.log('Loaded Datatables CSS');
loadScript(this, DATATABLES_JS).then(() => {
console.log('Loaded Datatables JS');
const table =
this.template.querySelector('.example-table');
const columnHeaders = ['Id', 'Name'];
let columnHeaderHtml = '<thead><tr>';
columnHeaders.forEach(function(header) {
columnHeaderHtml += '<th>' + header + '</th>';
});
columnHeaderHtml += '</tr></thead>';
table.innerHTML = columnHeaderHtml;
let dataTable = $(table).DataTable(); // Here is when it went wrong
this.recordsQueried.forEach(function(r) {
dataTable.row.add([
r.Id,
r.Name
]);
})
dataTable.draw();
})
})
})
}
}