[React] DataTable.isDataTable() not working?
[React] DataTable.isDataTable() not working?
Link to test case: https://stackblitz.com/edit/datatables-net-react-simple-2t2khp?file=src%2FApp.tsx
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem: I want to reinitialize the table since I may have different table headers to render.
Before I was using the DataTable.isDataTable() to detect if the table is initialized before:
if ($.fn.DataTable.isDataTable('#example')) {
$('#example').DataTable().clear().destroy();
// since headers will change
$("#example thead").remove();
$('#example tbody').remove();
}
This works very good but in React, I use:
const table = useRef(null);
useEffect(() => {
if ($.fn.DataTable.isDataTable($(table.current))) {
$(table.current).DataTable().clear().destroy();
// since headers will change
$(table.current).find('thead').remove();
$(table.current).find('tbody').remove();
}
}, [tableData]);
The DataTable.isDataTable() is always return false! Even with id passed to the <DataTable>:
useEffect(() => {
if ($.fn.DataTable.isDataTable('#example')) {
$('#example').DataTable().clear().destroy();
// since headers will change
$("#example thead").remove();
$('#example tbody').remove();
}
}, [tableData]);
<DataTable
id="example"
className="display"
data={tableData}
columns={columns}
>
</DataTable>
Am I doing something wrong or is it not supported in React?
Answers
Or more intuitively if it can automatically react to the data changes including the columns (headers), that would be great so we don't need to manually destroy the table and the
theadandtbodyhttps://datatables.net/manual/react#Reactive-data
I also tried to set the option
destroytotruebut it seems not working as well.The
idproperty isn't used on the JSX element, so it isn't propagated to the DOM element, thus it will always return false.Sounds like a good idea for an enhancement though.
Allan
Hi Allan,
Thanks for the hint. I have added the
idproperty in the source code. DataTable.isDataTable()` is returned normally as a result. But after the call of:before the data changes, the entire table is not reinitialized normally.
And then I found a solution that is much, much simpler than I thought.
No need to destroy the table and remove the
theadand thetbody.Just simply add a
keyto the <DataTable>e.g.
React will unmount for us when the columns are changed. So no more errors! Cheers!
Awesome - nice tip!
Hi Allan,
also in order to remove the warning message using React development mode:
in the
datatables.net-react:should be changed to
or
The warning message will disappear then.
Thank you! Fix committed and will be published with the next release.
Allan