I was trying to create a new LWC importing a third-party library that we already used in the past with VF but within a LWC. We decided to use this one instead of lightning-datatable because we need a real-time filtering feature.
Following the LoadScript documentation, we imported both jQuery and DataTable libraries to Static Resources but when running the component we always get a "this.template.querySelector(...).DataTable is not a function"
Find hereby the html and js file of our component:
filteredTable.html
<template>
<lightning-card title="OST Events">
<lightning-layout>
<lightning-layout-item>
<table id="table_id" class="example">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
</tr>
</tbody>
</table>
<template if:true={error}>
<c-error-panel errors={error}></c-error-panel>
</template>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
filteredTable.js:
import { LightningElement, track } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import DATATABLE from '@salesforce/resourceUrl/dataTablesv10_18';
import JQUERY from '@salesforce/resourceUrl/jQuery';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class FilteredTable extends LightningElement {
DataTable;
@track error;
@track dataExample;
@track successMessage = '';
dataTablejsInitialized = false;
renderedCallback() {
if (this.dataTablejsInitialized) {
return;
}
this.dataTablejsInitialized = true;
loadScript(this,JQUERY)
.then(()=>{
Promise.all([
loadScript(this, DATATABLE+'/DataTables-1.10.18/js/jquery.dataTables.min.js'),
loadStyle(this, DATATABLE+'/DataTables-1.10.18/css/jquery.dataTables.min.css')
])
.then(()=>{
this.showSuccessMessage();
})
.catch(error => {
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading DataTables',
message: error.message,
variant: 'error'
})
);
});
})
.catch(error => {
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading DataTables',
message: error.message,
variant: 'error'
})
);
});
}
showSuccessMessage() {
// eslint-disable-next-line no-undef
this.template.querySelector('.example').DataTable();
}
}
I followed the library documentation hereby: https://datatables.net/examples/data_sources/dom.html
Thanks! edit: Deleted a test line with the standard jQuery selector that I tested and corrected the selector to only match .example class.