Last active
February 28, 2021 08:21
-
-
Save anthonyjoeseph/b19ae3be9648a4ec176b054bfbd929f6 to your computer and use it in GitHub Desktop.
Typesafe Table W/O 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 * 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