Skip to content

Instantly share code, notes, and snippets.

@Lbatson
Last active February 1, 2021 18:45
Show Gist options
  • Save Lbatson/b42a30e49e6ddb946f55d26e8c895d75 to your computer and use it in GitHub Desktop.
Save Lbatson/b42a30e49e6ddb946f55d26e8c895d75 to your computer and use it in GitHub Desktop.
Simple generic table using React
import _ from 'lodash';
import React, { Component } from 'react';
class Table extends Component {
render() {
const { columns, data } = this.props;
// spread two-dimensional array to arguments for zip
// destructure resulting array elements from zip
let [names, props] = _.zip(...columns);
// build column headers with name values
let headers = <tr>{names.map((name, n) => <th key={n}>{name}</th>)}</tr>
// build rows with corresponding properties from the data for each column
let rows = data.map((item, i) => <tr key={i}>{props.map((prop, p) => <td key={p}>{item[prop]}</td>)}</tr>);
return (
<table className="table">
<thead>{headers}</thead>
<tbody>{rows}</tbody>
</table>
);
}
};
export default Table;
// usage: 2D array, first element = column name, second element: property of object in data array
// order added = order of columns presented in the table
const columns = [['Client', 'ClientName'], ['Payer', 'Payer']];
// data should be an array of objects
<Table columns={columns} data={data}/>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment