Categories
JavaScript Answers

How to create a simple table with React and JavaScript?

Spread the love

Sometimes, we want to create a simple table with React and JavaScript.

In this article, we’ll look at how to create a simple table with React and JavaScript.

How to create a simple table with React and JavaScript?

To create a simple table with React and JavaScript, we can use the array map method.

For instance, we write:

import React from "react";

const arr = [
  { firstName: "john", lastName: "smith" },
  { firstName: "jane", lastName: "doe" },
  { firstName: "mary", lastName: "smith" }
];

export default function App() {
  const rows = arr.map((a) => {
    const { firstName, lastName } = a;
    return (
      <tr>
        <td>{firstName}</td>
        <td>{lastName}</td>
      </tr>
    );
  });

  return (
    <div>
      <table>
        <tbody>{rows}</tbody>
      </table>
    </div>
  );
}

We call arr.map with a callback that returns the table rows which we create by populating it with the arr entry’s values.

Then we put the row in between the tbody tags to add the rows as the children of tbody.

Therefore, we see:

john	smith
jane	doe
mary	smith

displayed.

Conclusion

To create a simple table with React and JavaScript, we can use the array map method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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