'How to make react table to scrollable?
I am trying to make react table scrollable horizontally and vertically but right now it is taking all the space according to the data. I want to make this table of fixed height and scrollable in both direction.
Table component:
import React from "react";
import { useTable } from "react-table";
const Table = ({ columns, data }) => {
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable({
columns,
data,
});
return (
<table {...getTableProps()} className="text-center">
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th
className="bg-primary-dark text-white p-4 text-center"
{...column.getHeaderProps()}
>
{column.render("Header")}
</th>
))}
</tr>
))}
</thead>
<tbody
{...getTableBodyProps()}
className="bg-primary-light text-primary-dark overflow-scroll"
>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
};
export default Table;
Table Container
import React, { useMemo } from "react";
import useData from "../../hooks/useData";
import Table from "./Table";
const TableSection = React.memo(({ query }) => {
const { data, runtime, error } = useData(query);
const column =
data.length > 0 &&
Object.keys(data[0]).map((key) => {
return {
Header: data[0][key],
accessor: key,
};
});
const columns = useMemo(() => column, [column]);
const queryData = useMemo(() => data.slice(1), [data]);
return (
<div className="col-start-2 col-end-3 row-start-3 row-end-4 text-white m-6">
<Table columns={columns} data={queryData} />
</div>
);
});
export default TableSection;
Solution 1:[1]
Define the style on the container you want to be fixed-height and scrollable.
maxHeight: "30rem",
overflow: "auto",
Solution 2:[2]
I know is late but others might be searching also for this, as I found no answers this worked pretty well; actually is simple, wrap always your React Table on a div and a className, then on CSS file do this:
.tableContainer{
background-color: #1E1F25;
border-radius: 20px;
height: 244px;
padding: 0 10px 10px 10px;
overflow: scroll;
}
The key is to have a fixed height for the div that is wrapping the table and overflow set to scroll. Also, you can keep the table header fixed by doing this:
Table thead{
position: sticky;
top: 0px;
margin: 0 0 0 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Archivec |
Solution 2 | Scene |