Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
let DataContext = React.createContext();
function DataTable({ children }) {
return <section className="data-table">{children}</section>;
}
function DataTableHead({ children }) {
return (
<header className="data-table-head">
<div className="data-table-row">{children}</div>
</header>
);
}
function DataTableBody({ data, keyFn, children }) {
return (
<section className="data-table-body">
{data.map(datum => (
<div key={keyFn(datum)} tabIndex={0} className="data-table-row">
<DataContext.Provider value={datum} children={children} />
</div>
))}
</section>
);
}
function DataTableCell({ name, children }) {
let datum = useContext(DataContext);
return (
<div className="data-table-cell" data-column={name}>
{children(datum)}
</div>
);
}
function ExampleDataTable() {
let data = [/* ... */];
return (
<DataTable>
<DataTableHead>{/* just column labels */}</DataTableHead>
<DataTableBody data={data} keyFn={datum => datum.id}>
<DataTableCell name="name">
{datum => <span>{datum.name}</span>}
</DataTableCell>
<DataTableCell name="age">
{datum => <span>{datum.age}</span>}
</DataTableCell>
<CustomCell name="custom" />
</DataTableBody>
</DataTable>
);
}
function CustomCell({ name }) {
let datum = useContext(DataContext);
return (
<div className="data-table-cell" data-column={name}>
<span>{datum.prop}</span>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.