React Tables - How To Render Tables In ReactJS

January 2, 2017

In this tutorial, we'll pass data as a prop to a

component and render said data.

We'll use the following:

  • props - When an element represents a user-defined component, it passes JSX attributes to this component as a single object called props.
  • The map() method, which creates a new array, calling a function on every element of the provided array.

Passing Table Data as Props

To render a table, we need data to display. We'll use an array of javascript objects comprised of vegetables.

const products = [{
  name: "onion",
  price: ".99",
  id: 1
}, {
  name: "pepper",
  price: "1.25",
  id: 2
}, {
  name: "broccoli",
  price: "3.00",
  id: 3
}];

We will then map this array of javascript objects to render each name, price, and id, enclosed in

tags.

The constant products is passed into

ReactDOM.render(
  <Table data={products} />,
  document.getElementById("root")
);

We will split our React table into two components, the

component and the component which renders the data.

We pass the data as a prop from

to where the data is displayed.

Complete Example

const products = [{
  name: "onion",
  price: ".99",
  id: 1
}, {
  name: "pepper",
  price: "1.25",
  id: 2
}, {
  name: "broccoli",
  price: "3.00",
  id: 3
}];
const TableRow = ({row}) => (
  <tr>
    <td key={row.name}>{row.name}</td>
    <td key={row.id}>{row.id}</td>
    <td key={row.price}>{row.price}</td>
  </tr>
)
const Table = ({data}) = (
  <table>
    {data.map(row => {
      <TableRow row={row} />
    })}
  </table>
)
ReactDOM.render(
  <Table data={products} />, 
  document.getElementById("root")
);

Here's a link to the live CodePen.

Using Material UI

For something a little sexier, you can also use Material-UI's table component. Here's how to get started.

npm i material-ui react-tap-event-plugin --save
import React from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
} from 'material-ui/Table';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
const MuiTable = () => (
  <Table>
    <TableHeader>
      <TableRow>
        <TableHeaderColumn>ID</TableHeaderColumn>
        <TableHeaderColumn>Name</TableHeaderColumn>
        <TableHeaderColumn>Status</TableHeaderColumn>
      </TableRow>
    </TableHeader>
    <TableBody>
      <TableRow>
        <TableRowColumn>1</TableRowColumn>
        <TableRowColumn>John Smith</TableRowColumn>
        <TableRowColumn>Employed</TableRowColumn>
      </TableRow>
    </TableBody>
  </Table>
);
const App = () => (
  <MuiThemeProvider>
    <MuiTable />
  </MuiThemeProvider>
);
ReactDOM.render(
  <App />,
  document.getElementById('app')
);