Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active June 24, 2022 23:51
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 sturmenta/fcc4c8b0c5a326b6bdb35b2ac6385f6b to your computer and use it in GitHub Desktop.
Save sturmenta/fcc4c8b0c5a326b6bdb35b2ac6385f6b to your computer and use it in GitHub Desktop.
simple react table
import React from 'react'
import { ClassNames, CSSObject } from '@emotion/react'
import { Column, useTable } from 'react-table'
import TextByScale from './TextByScale'
interface Props {
columns: Array<Column>
data: Array<any>
}
const Table: React.FC<Props> = ({ columns: _columns, data: _data }) => {
const columns = React.useMemo(() => _columns, [])
const data = React.useMemo(() => _data, [])
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, data })
return (
<ClassNames>
{({ css }) => (
<div className={css(st.tableContainer)}>
<div className={css(st.theadSeparatorLine)} />
<table {...getTableProps()} className={css(st.table)}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()} className={css(st.header)}>
<TextByScale bold scale="body2">
{column.render('Header')}
</TextByScale>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()} className={css(st.cell)}>
<TextByScale scale="body2">
{cell.render('Cell')}
</TextByScale>
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
</div>
)}
</ClassNames>
)
}
const headerHeight = 64
const st: CSSObject = {
tableContainer: {
flex: 1,
display: 'flex',
height: '100%', //important
overflowY: 'auto', //important
flexDirection: 'column',
},
table: {
width: '100%',
'thead,tr,th': {
position: 'sticky',
top: 0,
},
th: {
backgroundColor: 'white',
fontWeight: 'revert',
},
'thead tr, tbody tr': {
'th:first-child,td:first-child': {
paddingLeft: 20,
},
'th:last-child,td:last-child': {
paddingRight: 20,
},
},
'tbody tr:hover': {
backgroundColor: '#d1dffa',
},
'th,td': {
margin: 0,
padding: 20,
paddingLeft: 10,
paddingRight: 10,
borderBottomWidth: 1,
borderBottomColor: '#eeeeee',
},
'tr:last-child td': {
borderBottomWidth: 0,
},
},
header: {
padding: '10px',
color: 'black',
textAlign: 'left',
height: headerHeight - 2,
},
theadSeparatorLine: {
borderBottomWidth: 2,
borderBottomColor: 'black',
marginTop: -2,
width: '100%',
position: 'sticky',
top: headerHeight - 2,
},
cell: {
padding: '10px',
},
}
// https://emotion.sh/docs/class-names
// https://emotion.sh/docs/object-styles
export default Table
@sturmenta
Copy link
Author

Screen Shot 2021-05-25 at 03 06 06

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment