Skip to content

Instantly share code, notes, and snippets.

@djirdehh
Created January 15, 2023 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djirdehh/6951b5f2c2eef20ca3574126eb1f7f58 to your computer and use it in GitHub Desktop.
Save djirdehh/6951b5f2c2eef20ca3574126eb1f7f58 to your computer and use it in GitHub Desktop.
Example of sorting and row selecting with React Table
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