Is it possible to create a responsive table using DataTable 1.13.4
and Bootstrap 5.2.3
? I encountered an issue while testing the table on a mobile device (using Firefox, not an actual device) where a small horizontal scrollbar appears, causing some columns to disappear.
Following the guidelines in the official DataTable documentation, I installed two dependencies via Yarn:
datatables.net-bs5
(DataTable for Bootstrap 5)datatables.net-responsive-bs5
(Plugin enabling responsiveness for Bootstrap 5)
I am aware of the need to add the Bootstrap 5 table-responsive
class before defining the table, but I also want to retain pagination and filtering. To achieve this, I included the dom
option in my JavaScript code when instantiating the DataTable object (
dom: 'f<"table-responsive"t>...
)
View the result on a desktop screen
View the result on a mobile screen
Although the screenshots may not show it, a small horizontal scrollbar appears on both desktop and mobile screens. On mobile devices, this scrollbar is so small (about 5/10 pixels) that it hides the Description
column, which is visible on desktop screens.
Here is my JavaScript file:
import {Controller} from '@hotwired/stimulus';
import DataTable from "datatables.net-bs5";
import "datatables.net-responsive-bs5";
export default class extends Controller {
connect() {
new DataTable('#tableMenu', {
pageLength: 5,
responsive: true,
dom: 'f<"table-responsive"t><"row"<"col-sm-12 col-lg-6 mb-3 mb-lg-0"i><"col-sm-12 col-lg-6 d-lg-flex justify-content-lg-end"p>>'
});
}
}
And here is my HTML file:
<table id="tableMenu" class="table table-striped">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Price</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for menu in menus %}
<tr>
<td>
<a href="{{ path('app.admin.menu.edit', {'id': menu.id}) }}" class="btn btn-primary">
<i class="fa fa-pen" style="font-size: 10px;"></i>
</a>
<button type="button"
id="delete-menu"
data-delete-url="{{ path('api.menu.delete', {'id': menu.id}) }}"
class="btn btn-danger">
<i class="fa fa-xmark" style="font-size: 10px;"></i>
</button>
</td>
<td>{{ menu.title }}</td>
<td>{{ menu.price / 100 }}€</td>
<td>{{ menu.description }}</td>
</tr>
{% endfor %}
<tfoot>
<tr>
<th></th>
<th>Title</th>
<th>Price</th>
<th>Description</th>
</tr>
</tfoot>
</table>
Thank you all for your assistance! 🫶