mirror of
https://github.com/gosticks/react-table.git
synced 2026-03-26 23:54:26 +00:00
153 lines
3.0 KiB
JavaScript
153 lines
3.0 KiB
JavaScript
import React from 'react'
|
|
import styled from 'styled-components'
|
|
import { useTable, useColumnOrder } from 'react-table'
|
|
|
|
import makeData from './makeData'
|
|
|
|
const Styles = styled.div`
|
|
padding: 1rem;
|
|
|
|
table {
|
|
border-spacing: 0;
|
|
border: 1px solid black;
|
|
|
|
tr {
|
|
:last-child {
|
|
td {
|
|
border-bottom: 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
th,
|
|
td {
|
|
margin: 0;
|
|
padding: 0.5rem;
|
|
border-bottom: 1px solid black;
|
|
border-right: 1px solid black;
|
|
background: white;
|
|
|
|
:last-child {
|
|
border-right: 0;
|
|
}
|
|
}
|
|
}
|
|
`
|
|
|
|
function shuffle(arr) {
|
|
arr = [...arr]
|
|
const shuffled = []
|
|
while (arr.length) {
|
|
const rand = Math.floor(Math.random() * arr.length)
|
|
shuffled.push(arr.splice(rand, 1)[0])
|
|
}
|
|
return shuffled
|
|
}
|
|
|
|
function Table({ columns, data }) {
|
|
const {
|
|
getTableProps,
|
|
getTableBodyProps,
|
|
headerGroups,
|
|
rows,
|
|
visibleColumns,
|
|
prepareRow,
|
|
setColumnOrder,
|
|
state,
|
|
} = useTable(
|
|
{
|
|
columns,
|
|
data,
|
|
},
|
|
useColumnOrder
|
|
)
|
|
|
|
const randomizeColumns = () => {
|
|
setColumnOrder(shuffle(visibleColumns.map(d => d.id)))
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
|
|
<table {...getTableProps()}>
|
|
<thead>
|
|
{headerGroups.map((headerGroup, i) => (
|
|
<tr {...headerGroup.getHeaderGroupProps()}>
|
|
{headerGroup.headers.map(column => (
|
|
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
|
|
))}
|
|
</tr>
|
|
))}
|
|
</thead>
|
|
<tbody {...getTableBodyProps()}>
|
|
{rows.slice(0, 10).map((row, i) => {
|
|
prepareRow(row)
|
|
return (
|
|
<tr {...row.getRowProps()}>
|
|
{row.cells.map((cell, i) => {
|
|
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
|
|
})}
|
|
</tr>
|
|
)
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
<pre>
|
|
<code>{JSON.stringify(state, null, 2)}</code>
|
|
</pre>
|
|
</>
|
|
)
|
|
}
|
|
|
|
function App() {
|
|
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(10), [])
|
|
|
|
return (
|
|
<Styles>
|
|
<Table columns={columns} data={data} />
|
|
</Styles>
|
|
)
|
|
}
|
|
|
|
export default App
|