'React Table - new order after filtering
I have a table made with React Table. I want it to have a fresh order after each filtering. So far, I have achieved only one order which is created at render.
Here is the Table component:
import React, { useEffect } from "react";
import { Table as BTable } from "react-bootstrap";
import { useTable, useSortBy, useGlobalFilter } from "react-table";
function Table({ data, columns, variant, filter = "" }) {
const {
getTableProps,
headerGroups,
rows,
prepareRow,
state,
setGlobalFilter,
} = useTable(
{
columns,
data,
},
useGlobalFilter,
useSortBy
);
const { globalFilter } = state;
useEffect(() => {
setGlobalFilter(filter);
// eslint-disable-next-line
}, []);
return (
<>
<span>Search: </span>
<input
value={globalFilter}
onChange={(e) => setGlobalFilter(e.target.value)}
onMouseMove={(e) => setGlobalFilter(e.target.value)}
></input>
<hr></hr>
<BTable striped bordered hover variant={variant} {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th
width={column.width}
{...column.getHeaderProps(column.getSortByToggleProps())}
>
{column.render("Header")}
<span>
{column.isSorted
? column.isSortedDesc
? " 🔽"
: " 🔼"
: ""}
</span>
</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
);
})}
</tr>
);
})}
</tbody>
</BTable>
</>
);
}
export default Table;
And implementation:
const columns = React.useMemo(
() => [
{
Header: "#",
Cell: (row) => {
return <div>{Number(row.row.id) + 1}</div>;
},
},
{
Header: "ID",
accessor: "id",
},
{
Header: "Added By",
accessor: "addedBy",
},
{ Header: "Date of creation", accessor: "dateOfCreation", width: "10%" },
{
Header: "Ordertaker",
accessor: "orderTaker",
width: "5%",
},
{
Header: "Customer",
accessor: "customer",
width: "20%",
},
{
Header: "Description",
accessor: "description",
disableSortBy: "true",
width: "30%",
},
{
Header: "Status",
accessor: "status",
disableSortBy: "true",
width: "10%",
},
],
);
return (
<Table
data={data} // data is fetched from firebase
columns={columns}
variant="dark"
/>
);
"#" column has number from 1 for each row. What I want is to reset order in "#" column after each filtering to start with 1. Any ideas how can it be done?
Solution 1:[1]
map returns are inherently ordered in the insertion order. You could try a sort before hand. Here's a link.
Something like this might work:
rows.sort((a, b) => a.# - b.#).map((row, i) => ...
Solution 2:[2]
I found the solution on the internet. Here`s the link
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 | tinkoh |
| Solution 2 | maciejpuzianowski |
