Example of sorting and row selecting with React Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { useTable, useSortBy, useRowSelect } from "react-table"; | |
function App() { | |
const columns = React.useMemo( | |
() => [ | |
{ | |
Header: "Name", | |
accessor: "name" | |
}, | |
{ | |
Header: "Age", | |
accessor: "age" | |
} | |
], | |
[] | |
); | |
const data = React.useMemo( | |
() => [ | |
{ | |
name: "James Bond", | |
age: 33 | |
}, | |
{ | |
name: "Ethan Hunt", | |
age: 32 | |
} | |
], | |
[] | |
); | |
const tableInstance = useTable( | |
{ columns, data }, | |
useSortBy, | |
useRowSelect, | |
(hooks) => { | |
hooks.visibleColumns.push((columns) => [ | |
// We make a new column for selection | |
{ | |
accessor: "selection", | |
disableSortBy: true, | |
Cell: ({ row }) => ( | |
<div> | |
<input type="checkbox" {...row.getToggleRowSelectedProps()} /> | |
</div> | |
) | |
}, | |
...columns | |
]); | |
} | |
); | |
const { | |
getTableProps, | |
getTableBodyProps, | |
headerGroups, | |
rows, | |
prepareRow, | |
state: { selectedRowIds } | |
} = tableInstance; | |
console.log("Selected Row Ids", selectedRowIds); | |
/* | |
use the headerGroups property to render the table header | |
*/ | |
const tableHead = ( | |
<thead> | |
{headerGroups.map((headerGroup) => ( | |
<tr {...headerGroup.getHeaderGroupProps()}> | |
{headerGroup.headers.map((column) => ( | |
<th {...column.getHeaderProps(column.getSortByToggleProps())}> | |
{column.render("Header")} | |
{/* Add a sort direction indicator */} | |
<span> | |
{column.isSorted ? (column.isSortedDesc ? " 🔽" : " 🔼") : ""} | |
</span> | |
</th> | |
))} | |
</tr> | |
))} | |
</thead> | |
); | |
/* | |
use the getTableBodyProps(), rows, and prepareRow() properties to render the table body | |
*/ | |
const tableBody = ( | |
<tbody {...getTableBodyProps()}> | |
{rows.map((row) => { | |
prepareRow(row); | |
return ( | |
<tr {...row.getRowProps()}> | |
{row.cells.map((cell) => { | |
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>; | |
})} | |
</tr> | |
); | |
})} | |
</tbody> | |
); | |
return ( | |
<table {...getTableProps()}> | |
{tableHead} | |
{tableBody} | |
</table> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment