I am using this DataTable, which works correctly, the problem is that when I run it I get this error: “DataTables warning: table id=example – Cannot reinitialise DataTable. For more information about this error, please see https://datatables.net/tn/3“, the solution was to use the following: ‘if ($.fn.DataTable.isDataTable(’#example”)) {
$(“#example”).DataTable().destroy();
}”. But now I have a new problem and I get a very wide and empty column at the end of the table, do you know how to solve it?
import React, { useEffect, useState } from "react";
import $ from "jquery";
import "datatables.net-bs5";
function MyDataTable() {
const [users] = useState([
{
id: 1,
nombre: "Axel",
primerApellido: "Rojero",
segundoApellido: "Flores",
curp: "HFKJALSITOSPR9AISK",
rfc: "DJU8ALS9F0SLD",
},
{
id: 2,
nombre: "Kira",
primerApellido: "Garfias",
segundoApellido: "Gonzalez",
curp: "HFKJALSITOSPR9AISK",
rfc: "DJU8ALS9F0SLD",
},
]);
useEffect(() => {
if ($.fn.DataTable.isDataTable("#example")) {
$("#example").DataTable().destroy();
}
$("#example").DataTable({
autoWidth: true,
paging: false,
searching: true,
colReorder: true,
fixedHeader: true,
responsive: true,
stateSave: true,
columns: [
{ title: "Numero de empleado" },
{ title: "Nombre" },
{ title: "Primer apellido" },
{ title: "Segundo apellido" },
{ title: "CURP" },
{ title: "RFC" },
{ title: "Editar" },
{ title: "Borrar" },
],
});
}, [users]);
return (
<div className="container mt-5">
<h2>Docentes</h2>
<div className="col mb-3">
<button type="button" className="btn btn-primary">
Agregar Usuario
</button>
</div>
<table
id="example"
className="table table-striped table-bordered"
style={{ width: "100%" }}
>
<thead>
<tr>
<th>Numero de empleado</th>
<th>Nombre</th>
<th>Primer apellido</th>
<th>Segundo apellido</th>
<th>CURP</th>
<th>RFC</th>
<th>Editar</th>
<th>Borrar</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.nombre}</td>
<td>{user.primerApellido}</td>
<td>{user.segundoApellido}</td>
<td>{user.curp}</td>
<td>{user.rfc}</td>
<td>
<button className="btn btn-warning">Editar</button>
</td>
<td>
<button className="btn btn-danger">Borrar</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default MyDataTable;
DataTable pre-destruction: Used $(“#example”).DataTable().destroy() before each initialization to avoid duplication when re-rendering the table.
Use of useEffect: Table initialization is performed inside useEffect, ensuring that the table is properly destroyed before being re-created.
Disabling of certain settings: Properties such as autoWidth and responsive were disabled to eliminate possible conflicts that could be causing the duplications.