I'm having an issue where react-table (version 7.1.0) seems to be reinitializing any time the page needs to be re-rendered. Using the code below (running example here) as an example, if you were to change the pageIndex value (by switching to a different page), then hit Dummy Button, you can observe that the pageIndex resets back to its default value of 0. The same thing happens if you modify the pageSize in that it automatically resets back to its default value of 10 any time the page has to be re-rendered.
import React, { useState } from "react";
import makeData from "./makeData";
import { useTable, usePagination } from "react-table";
import { ButtonToolbar, Button, Table } from "react-bootstrap";
// Nonsense function to force page to be rendered
function useForceUpdate() {
const [value, setValue] = useState(0);
return () => setValue(value => ++value);
}
export default function App() {
const forceUpdate = useForceUpdate();
const columns = React.useMemo(
() => [
{
Header: "Name",
columns: [
{
Header: "First Name",
accessor: "firstName"
},
{
Header: "Last Name",
accessor: "lastName"
}
]
},
{
Header: "Info",
columns: [
{
Header: "Age",
accessor: "age"
},
{
Header: "Visits",
accessor: "visits"
},
{
Header: "Status",
accessor: "status"
},
{
Header: "Profile Progress",
accessor: "progress"
}
]
}
],
[]
);
const data = React.useMemo(() => makeData(100000), []);
let ArchiveTable = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
state: { pageIndex, pageSize }
} = useTable(
{
columns,
data
},
usePagination
);
return (
<div style={{ textAlign: "center" }}>
<Table striped bordered {...getTableProps()} className="datasets">
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.render("Header")}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{page.map((row, i) => {
prepareRow(row);
return (
<tr
{...row.getRowProps()}
className={row.isSelected ? "selected" : row.className}
>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
);
})}
</tr>
);
})}
</tbody>
</Table>
<div className="pagination" style={{ display: "inline-block" }}>
<ButtonToolbar>
<Button
variant="light"
onClick={() => gotoPage(0)}
disabled={!canPreviousPage}
size="small"
>
<span><<</span>
</Button>
<Button
variant="light"
onClick={previousPage}
disabled={!canPreviousPage}
size="small"
>
<span><</span>
</Button>
<select
value={pageSize}
onChange={e => {
setPageSize(Number(e.target.value));
}}
>
{[5, 10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
<Button
variant="light"
onClick={nextPage}
disabled={!canNextPage}
size="small"
>
<span>></span>
</Button>
<Button
variant="light"
onClick={() => gotoPage(pageCount - 1)}
disabled={!canNextPage}
size="small"
>
<span>>></span>
</Button>
</ButtonToolbar>
<span>
Page <strong>{pageOptions.length === 0 ? 0 : pageIndex + 1}</strong>{" "}
of <strong>{pageOptions.length}</strong>
</span>
</div>
</div>
);
};
return (
<div className="App">
<ArchiveTable data={data} columns={columns} />
<button onClick={forceUpdate}>Dummy Button</button>
</div>
);
}
I'm at a complete loss for what to do to fix this. What is the proper way to set everything up so that I don't reinitialize react-table every time the page has to be re-rendered? Said another way, if I hit the Dummy Button, I don't want the table to reset back to page 1 with a page size of 10.
Ended up figuring out the answer. The problem was I needed to move the initialization of the table outside of the rendering logic (quite obvious, in hindsight). Basically, I simply created an ArchiveTable function. For anybody who stumbles across this, you can check here for a working example.
function ArchiveTable({ columns, data }) {
// Add all the initialization and table rendering code here
// (everything that was originally part of the ArchiveTable initialization)
}
Related
I have a slightly modified implementation of the react-table v8 filters: https://tanstack.com/table/v8/docs/examples/react/filters
In the original they seem to use a custom filter function to filter the table globally but it requires another library that i don't want to include, the documentation isn't very clear about this but there seems to be built-in functions that i can use: https://tanstack.com/table/v8/docs/api/features/filters
However the table stops filtering as soon as i change it, i tried not including the globalFilterFn as well as setting it to globalFilterFn: "includesString" which is one of the built-in functions i mentioned but nothing has worked so far.
here is my code:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import {
useReactTable,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
FilterFn,
ColumnDef,
flexRender
} from "#tanstack/react-table";
//import { RankingInfo, rankItem } from "#tanstack/match-sorter-utils";
import { makeData, Person } from "./makeData";
/* declare module "#tanstack/table-core" {
interface FilterMeta {
itemRank: RankingInfo;
}
}
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
// Rank the item
const itemRank = rankItem(row.getValue(columnId), value);
// Store the itemRank info
addMeta({
itemRank
});
// Return if the item should be filtered in/out
return itemRank.passed;
}; */
function App() {
const rerender = React.useReducer(() => ({}), {})[1];
const [globalFilter, setGlobalFilter] = React.useState("");
const columns = React.useMemo<ColumnDef<Person>[]>(
() => [
{
header: "Name",
footer: (props) => props.column.id,
columns: [
{
accessorKey: "firstName",
cell: (info) => info.getValue(),
footer: (props) => props.column.id
},
{
accessorFn: (row) => row.lastName,
id: "lastName",
cell: (info) => info.getValue(),
header: () => <span>Last Name</span>,
footer: (props) => props.column.id
},
{
accessorFn: (row) => `${row.firstName} ${row.lastName}`,
id: "fullName",
header: "Full Name",
cell: (info) => info.getValue(),
footer: (props) => props.column.id
}
]
},
{
header: "Info",
footer: (props) => props.column.id,
columns: [
{
accessorKey: "age",
header: () => "Age",
footer: (props) => props.column.id
},
{
header: "More Info",
columns: [
{
accessorKey: "visits",
header: () => <span>Visits</span>,
footer: (props) => props.column.id
},
{
accessorKey: "status",
header: "Status",
footer: (props) => props.column.id
},
{
accessorKey: "progress",
header: "Profile Progress",
footer: (props) => props.column.id
}
]
}
]
}
],
[]
);
const [data, setData] = React.useState(() => makeData(500));
const refreshData = () => setData((old) => makeData(500));
const table = useReactTable({
data,
columns,
state: {
globalFilter
},
onGlobalFilterChange: setGlobalFilter,
//globalFilterFn: "includesString",
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel()
});
return (
<div className="p-2">
<div>
<input
value={globalFilter ?? ""}
onChange={(event) => setGlobalFilter(event.target.value)}
className="p-2 font-lg shadow border border-block"
placeholder="Search all columns..."
/>
</div>
<div className="h-2" />
<table>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder ? null : (
<>
<div
{...{
className: header.column.getCanSort()
? "cursor-pointer select-none"
: "",
onClick: header.column.getToggleSortingHandler()
}}
>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
{{
asc: " 🔼",
desc: " 🔽"
}[header.column.getIsSorted() as string] ?? null}
</div>
</>
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
<div className="h-2" />
<div className="flex items-center gap-2">
<button
className="border rounded p-1"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
{"<<"}
</button>
<button
className="border rounded p-1"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
{"<"}
</button>
<button
className="border rounded p-1"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
{">"}
</button>
<button
className="border rounded p-1"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
{">>"}
</button>
<span className="flex items-center gap-1">
<div>Page</div>
<strong>
{table.getState().pagination.pageIndex + 1} of{" "}
{table.getPageCount()}
</strong>
</span>
<span className="flex items-center gap-1">
| Go to page:
<input
type="number"
defaultValue={table.getState().pagination.pageIndex + 1}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) - 1 : 0;
table.setPageIndex(page);
}}
className="border p-1 rounded w-16"
/>
</span>
<select
value={table.getState().pagination.pageSize}
onChange={(e) => {
table.setPageSize(Number(e.target.value));
}}
>
{[10, 20, 30, 40, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
<div>{table.getPrePaginationRowModel().rows.length} Rows</div>
<div>
<button onClick={() => rerender()}>Force Rerender</button>
</div>
<div>
<button onClick={() => refreshData()}>Refresh Data</button>
</div>
<pre>{JSON.stringify(table.getState(), null, 2)}</pre>
</div>
);
}
const rootElement = document.getElementById("root");
if (!rootElement) throw new Error("Failed to find the root element");
ReactDOM.createRoot(rootElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
a link to CodeSanbox with it: https://codesandbox.io/s/long-monad-652jcm?file=/src/main.tsx
I'm still very inexperienced in React and even more with typescript so maybe i'm missing something obvious.
am i misinterpreting the docs, maybe the custom function is necessary?
There is a current issue on GitHub where you can't use a global filter if one of your column is using number fields. You can simply solve it by replacing the number by a string in your data. (.toString(), and sorting still works). If worked fine for me afterwards. :)
Your globalFilter doesn't do anything, you need to test if the contents of the table are equal to the filter or not.
I am trying to find out how to get the number of selected rows from react table.
Also I would like to send the number of selected rows into another sibling component, which would enable or disable based on the number of rows selected(minimum of 10).
Please Help. I would also be helpful if anyone could design a modal where I can edit a value of a selected row (only if a row is selected) in the table with value showing in edit modal.
import React, { useState } from 'react'
import { useMemo } from 'react'
import table from '../assets/json/mock.json'
import { useTable,useRowSelect, useSortBy, usePagination} from 'react-table';
import {useSticky} from 'react-table-sticky'
const Table =({columns,data})=> {
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
page,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
pageOptions,
state,
gotoPage,
pageCount,
setPageSize,
selectedFlatRows,
prepareRow,
}=useTable({
columns,
data,
initialState : {pageIndex : 0}
},
useSortBy,usePagination,useRowSelect,
hooks => {
hooks.visibleColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
])
}
)
const {pageIndex,pageSize,selectedRowIds}=state
return (
<>
<table className="database-table sticky" {...getTableProps()}>
<thead className='header'>
{
headerGroups.map((headerGroup)=>
(
<tr {...headerGroup.getHeaderGroupProps()}>
{
headerGroup.headers.map((column) =>
(
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render(`Header`)}
<span>
{
column.isSorted ? (column.isSortedDesc ? 'â–¼':'â–²'):''
}
</span>
</th>
))
}
</tr>
))
}
</thead>
<tbody {...getTableBodyProps()}>
{
page.map((row)=>
{
prepareRow(row)
return(
<tr {...row.getRowProps()}>
{row.cells.map((cell)=>{
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})
}
</tbody>
</table>
<div className='header-bottom'>
{
headerGroups.map((headerGroup)=>
(
<tr {...headerGroup.getHeaderGroupProps()}>
{
headerGroup.headers.map((column) =>
(
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render(`Header`)}
<span>
{
column.isSorted ? (column.isSortedDesc ? 'â–¼':'â–²'):''
}
</span>
</th>
))
}
</tr>
))
}
</div>
<div className='table-footer'>
<div className='page-no'id='modal-item'>
Viewing : {pageIndex+1} of {pageOptions.length}
</div>
<span className ='copyright'>
© 2022 Highradius.All Rights Reserved
</span>
<span className='rowno' id='modal-item'>
Rows per Page :
<select value={pageSize} onChange={e=>setPageSize(Number(e.target.value))}>
{
[10,20,30,40,50].map(pageSize=>(
<option key={pageSize} value={pageSize}>
{pageSize }
</option>
))
}
</select>
</span>
<button button onClick={()=>previousPage()} disabled={!canPreviousPage} id='pag-btn'>{' < '}</button>
<button button onClick={()=>nextPage()} disabled={!canNextPage} id='pag-btn' >{' > '}</button>
</div>
</>
)
}
export default Table
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Add
selectedFlatRows,
state: { selectedRowIds },
after prepareRow, in const.
You can print the selected rows like this.
<p>Selected Rows: {Object.keys(selectedRowIds).length}</p>
<pre>
<code>
{JSON.stringify(
{
selectedRowIds: selectedRowIds,
'selectedFlatRows[].original': selectedFlatRows.map(d => d.original),
},
null,
2
)}
</code>
</pre>
A working example is here: https://codesandbox.io/s/naughty-pond-3e5jp
I am new to REACT and having trouble getting a table component to work correctly.
I am using the react-tables package and the tutorial example here but I am doing everything in a table.js component file and adding it to my App.js. Basically, I am trying to create a table with pagination, sorting, and selectable rows with checkboxes. My issue is that I am only getting the checkboxes to populate in the header (see below).
Here is my code; what am I doing incorrectly here? Note - my rows are being created using page, not row and are coming from my API. Any suggestions on how to fix this?
import React, { useMemo, useEffect, useState } from 'react'
import reactTable, {useTable, useRowSelect, usePagination, useSortBy} from 'react-table'
import axios from "axios";
import { COLUMNS } from './columns'
import './Table.css'
export const Table = () => {
const [loadingData, setLoadingData] = useState(true);
const columns = useMemo(() => COLUMNS, []);
const [data, setData] = useState([]);
const IndeterminateCheckbox = React.forwardRef(
//This is the function for the checkboxes in page select
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
useEffect(() => {
async function getData() {
await axios
.get("http://localhost:5000/my/api")
.then((response) => {
// check if the data is populated
console.log(response.data);
setData(response.data);
// you tell it that you had the result
setLoadingData(false);
});
}
if (loadingData) {
// if the result is not ready so you make the axios call
getData();
}
}, []);
const tableInstance = useTable({
columns,
data,
initialState: { pageIndex: 2 }
}, useSortBy,
usePagination,
useRowSelect,
hooks => {
hooks.visibleColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllPageRowsSelectedProps }) => (
<div>
<IndeterminateCheckbox {...getToggleAllPageRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
])
}
);
const { getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page, //Begins the pagination and select stuff
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
selectedFlatRows,
state: { pageIndex, pageSize, selectedRowIds }} = tableInstance
return (
<div className="container">
{loadingData ? (
<p>Loading Please wait...</p>
) : (
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{
headerGroup.headers.map((column) =>(
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render('Header')}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{
page.map((row, i) => {
prepareRow(row);
return(
<tr {...row.getRowProps()}>
{
row.cells.map(cell => {
console.log(cell.render('Cell').props.value);
//<td {...cell.getCellProps()}>{cell.render('Cell').props.value}</td>
return <td>{cell.render('Cell').props.value}</td>
})
}
</tr>
)
})
}
</tbody>
</table>
)}
<div className="pagination">
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
{'<<'}
</button>{' '}
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
{'<'}
</button>{' '}
<button onClick={() => nextPage()} disabled={!canNextPage}>
{'>'}
</button>{' '}
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
{'>>'}
</button>{' '}
<span>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{' '}
</span>
<span>
| Go to page:{' '}
<input
type="number"
defaultValue={pageIndex + 1}
onChange={e => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
gotoPage(page)
}}
style={{ width: '100px' }}
/>
</span>{' '}
</div>
</div>
)
}
Return <td {...cell.getCellProps()}>{cell.render('Cell')}</td> from tr.
This should work:
<tbody {...getTableBodyProps()}>
{page.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td> // fix return statement
);
})}
</tr>
);
})}
</tbody>
I literally have stayed up all night trying to figure out how to grab a value from my row.
const columns = useMemo(
() => [
{
// first group - TV Show
Header: "Shop Chop Chop List",
// First group columns
columns: [
{
Header: "User",
accessor: "email",
},
{
Header: "Store",
accessor: "store",
},
],
},
{
Header: "Details",
columns: [
{
Header: "Item",
accessor: "title",
},
{
Header: "Picture",
accessor: "picture",
Cell: ({ row }) => (
<a
target="_blank"
rel="noopener noreferrer"
href={row.original.picture}
>
{row.original.picture}
</a>
),
},
{
Header: "Aisle",
accessor: "aisleLocation",
},
{
Header: "Location",
id: 'edit',
accessor: 'id',
Cell: ({value}) => (
<div>
<button
onClick={()=> {
console.log(value);
}}
className={styles.editBtn}
>
Record Aisle
</button>
</div>
),
},
{
Header: "Remove",
id: "delete",
accessor: (str) => "delete",
Cell: (row)=> (
<button
className={styles.deleteBtn}
onClick={()=> {
const dataCopy = [...data];
dataCopy.splice(row.index, 1);
setData(dataCopy);
}}>
Found
</button>
)
}
],
},
],
[data],
);
This is my latest attempt. I am trying to grab a value from this row so I can assign a aisle location on the back end. I would prefer the uniqueID, but I could make it work with title and store as well. It is so damn hard to grab the information out of this row.
Here is my tableContainer
import React, { Fragment } from 'react';
import {
useTable,
useSortBy,
useFilters,
useExpanded,
usePagination,
} from 'react-table';
import { Table, Row, Col, Button, Input} from 'reactstrap';
import { Filter, DefaultColumnFilter } from './Filters';
const TableContainer = ({ columns, data, renderRowSubComponent }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
prepareRow,
visibleColumns,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
state: { pageIndex },
} = useTable(
{
columns,
data,
defaultColumn: { Filter: DefaultColumnFilter },
initialState: { pageIndex: 0, pageSize: 5 },
},
useFilters,
useSortBy,
useExpanded,
usePagination
);
const generateSortingIndicator = (column) => {
return column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : '';
};
const onChangeInInput = (event) => {
const page = event.target.value ? Number(event.target.value) - 1 : 0;
gotoPage(page);
};
return (
<Fragment>
<Table bordered hover {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>
<div {...column.getSortByToggleProps()}>
{column.render('Header')}
{generateSortingIndicator(column)}
</div>
<Filter column={column} />
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{page.map((row) => {
prepareRow(row);
return (
<Fragment key={row.getRowProps().key}>
<tr onClick={()=> handleShow(row.original)}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
);
})}
</tr>
{row.isExpanded && (
<tr>
<td colSpan={visibleColumns.length}>
{renderRowSubComponent(row)}
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</Table>
Please, can anyone help? I am new so very specific instructions are desired
please, and thank you
react-table is meant for displaying the data, not the JSX element but you can solve the issue in two ways, first, you can pass a unique id in the row data and just like above use that in the Cell or you can just render the JSX element as a row data and use the unique id directly(for example some model Id which you are trying to delete) but rendering the JSX element as a data is a heavy task as memoization will fail and you will have to do provide extra logic to prevent rerendering.
I'm using react-table to include the rows and pagination in the table as shown in this example: https://react-table.tanstack.com/docs/examples/row-selection-and-pagination.
I've done my example as the tutorial says, but it doesn't function as intended. I can only select 1 row before it stops updating the selectedRowsId. Deselecting the row doesn't clear it either. What am I doing wrong?
import React, { useMemo, forwardRef, useRef, useEffect } from "react";
import {
useTable,
useSortBy,
useFilters,
useGlobalFilter,
usePagination,
useRowSelect
} from "react-table";
import matchSorter from "match-sorter";
import '../../static/scss/table.scss'
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length;
return (
<input
value={filterValue || ""}
onChange={(e) => {
setFilter(e.target.value || undefined); // Set undefined to remove the filter entirely
}}
placeholder={`Search ${count} records...`}
/>
);
}
function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the options for filtering
// using the preFilteredRows
const options = React.useMemo(() => {
const options = new Set();
preFilteredRows.forEach((row) => {
options.add(row.values[id]);
});
return [...options.values()];
}, [id, preFilteredRows]);
// Render a multi-select box
return (
<select
value={filterValue}
onChange={(e) => {
setFilter(e.target.value || undefined);
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
);
}
function fuzzyTextFilterFn(rows, id, filterValue) {
return matchSorter(rows, filterValue, { keys: [(row) => row.values[id]] });
}
fuzzyTextFilterFn.autoRemove = (val) => !val;
const IndeterminateCheckbox = forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = useRef()
const resolvedRef = ref || defaultRef
useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
export default function Table({ data }) {
console.log(data[0].title);
const filterTypes = useMemo(
() => ({
// Add a new fuzzyTextFilterFn filter type.
fuzzyText: fuzzyTextFilterFn,
// Or, override the default text filter to use
// "startWith"
text: (rows, id, filterValue) => {
return rows.filter((row) => {
const rowValue = row.values[id];
return rowValue !== undefined
? String(rowValue)
.toLowerCase()
.startsWith(String(filterValue).toLowerCase())
: true;
});
},
}),
[]
);
const defaultColumn = useMemo(
() => ({
// Let's set up our default Filter UI
Filter: DefaultColumnFilter,
}),
[]
);
const columns = useMemo(
() => [
{
Header: "Naziv",
accessor: "title",
},
{
Header: "Tip",
accessor: "activity_type_id",
Filter: SelectColumnFilter,
filter: "includes",
},
{
Header: "Datum",
accessor: "start_time",
},
{
Header: "Mjesto",
accessor: "location",
},
{
Header: "Organizator",
accessor: "team_id",
Filter: SelectColumnFilter,
filter: "includes",
},
{
Header: "Odgovorna osoba",
accessor: "user_id",
},
],
[]
);
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
prepareRow,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
selectedFlatRows,
state: { pageIndex, pageSize, selectedRowIds },
} = useTable(
{
columns,
data,
defaultColumn,
filterTypes,
initialState: { pageIndex: 0 },
},
useFilters,
useGlobalFilter,
useSortBy,
usePagination,
useRowSelect,
hooks => {
hooks.visibleColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllPageRowsSelectedProps }) => (
<div>
<IndeterminateCheckbox {...getToggleAllPageRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
])
}
);
return (
<div>
<legend className="legend">Popis aktivnosti</legend>
<>
<pre>
<code>
{JSON.stringify(
{
pageIndex,
pageSize,
pageCount,
canNextPage,
canPreviousPage,
},
null,
2
)}
</code>
</pre>
<table {...getTableProps()}>
<thead>
{
// Loop over the header rows
headerGroups.map((headerGroup) => (
// Apply the header row props
<tr {...headerGroup.getHeaderGroupProps()}>
{
// Loop over the headers in each row
headerGroup.headers.map((column) => (
// Apply the header cell props
<th
{...column.getHeaderProps(
column.getSortByToggleProps()
)}
>
{
// Render the header
column.render("Header")
}
<span>
{column.isSorted
? column.isSortedDesc
? " 🔽"
: " 🔼"
: ""}
</span>
</th>
))
}
{}
<th>Nige</th>
<th>Nei</th>
</tr>
))
}
{
// Loop over the header rows
headerGroups.map((headerGroup) => (
// Apply the header row props
<tr {...headerGroup.getHeaderGroupProps()}>
{
// Loop over the headers in each row
headerGroup.headers.map((column) => (
// Apply the header cell props
<th>
<div>
{column.canFilter ? column.render("Filter") : null}
</div>
</th>
))
}
{}
<th></th>
<th></th>
</tr>
))
}
</thead>
{/* Apply the table body props */}
<tbody {...getTableBodyProps()}>
{page.map((row, i) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
<div className="pagination">
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
{"<<"}
</button>{" "}
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
{"<"}
</button>{" "}
<button onClick={() => nextPage()} disabled={!canNextPage}>
{">"}
</button>{" "}
<button
onClick={() => gotoPage(pageCount - 1)}
disabled={!canNextPage}
>
{">>"}
</button>{" "}
<span>
Page{" "}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{" "}
</span>
<span>
| Go to page:{" "}
<input
type="number"
defaultValue={pageIndex + 1}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) - 1 : 0;
gotoPage(page);
}}
style={{ width: "100px" }}
/>
</span>{" "}
<select
value={pageSize}
onChange={(e) => {
setPageSize(Number(e.target.value));
}}
>
{[10, 20, 30, 40, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
<p>Selected Rows: {Object.keys(selectedRowIds).length}</p>
<pre>
<code>
{JSON.stringify(
{
selectedRowIds: selectedRowIds,
'selectedFlatRows[].original': selectedFlatRows.map(
d => d.original
),
},
null,
2
)}
</code>
</pre>
</>
</div>
);
}
I found the solution. index.js file has the <React.StrictMode> wrapping the <App />. Removing the <React.StrictMode> fixes it and functions properly. This is probably a bug and should be fixed.