Skip to content

Instantly share code, notes, and snippets.

@anthonyjoeseph
Last active February 28, 2021 08:21
Show Gist options
  • Save anthonyjoeseph/b19ae3be9648a4ec176b054bfbd929f6 to your computer and use it in GitHub Desktop.
Save anthonyjoeseph/b19ae3be9648a4ec176b054bfbd929f6 to your computer and use it in GitHub Desktop.
Typesafe Table W/O React Table
import React from 'react'
import * as A from 'fp-ts/Array';
const Table2 = <A,>({
data, order, headerTitles, rowRenderer
}: {
data: A[]
order: NonNullable<keyof A>[]
headerTitles: {
[K in NonNullable<keyof A>]: string
}
rowRenderer: {
[K in NonNullable<keyof A>]: (val: A[K]) => JSX.Element
}
}) => (
<table>
<thead>
<tr>
{order.map((key) => (
<th>{headerTitles[key]}</th>
))}
</tr>
</thead>
<tbody>
{data.map(row => (
<tr>
{order.map(key => (
<td>{rowRenderer[key](row[key])}</td>
))}
</tr>
))}
</tbody>
</table>
)
interface TestData { firstName: string; lastName: string; strength: number }
const TestDataTable = ({ testDatas }: { testDatas: TestData[] }) => (
<Table2
data={testDatas}
order={['firstName', 'lastName', 'strength']}
headerTitles={{
firstName: "First Name",
lastName: "Uppercase Last Name",
strength: "Strength Plus 2",
}}
rowRenderer={{
firstName: (firstName) => <div>{firstName}</div>,
lastName: (lastName) => <div>{lastName.toUpperCase()}</div>,
strength: (strength) => <div>{strength + 2}</div>
}}
/>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment