Categories
JavaScript React

Reactjs Table Example

Spread the love

To make a table with React, we just need to use the table element as we do with regular HTML.

Then we use the table, thead, tbody, tr and th elements as follows:

import React from "react";

const data = [
  { id: 1, firstName: "jane", lastName: "doe" },
  { id: 2, firstName: "joe", lastName: "smith" },
  { id: 3, firstName: "may", lastName: "jones" }
];

export default function App() {
  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>first name</th>
            <th>last name</th>
          </tr>
        </thead>
        <tbody>
          {data.map(d => (
            <tr key={d.id}>
              <td>{d.firstName}</td>
              <td>{d.lastName}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

We have the data array, which we map to table rows in between the tbody tags.

The thead has the table headings with the tr for the rows and th for the table headings.

The entries in data are mapped to tr elements with td for the cells.

Then we would get a table with the fields we have in the objects.

Now we have a table with dynamic data in it.

Leave a Reply

Your email address will not be published. Required fields are marked *