DEV Community

Cover image for React Dynamic Table | Programming Tutorial
Labby for LabEx

Posted on

React Dynamic Table | Programming Tutorial

Introduction

MindMap

In this lab, we will explore how to use React to dynamically render a table with rows created from an array of primitives. Specifically, we will utilize the Array.prototype.map() method to map each item in the data array to a <tr> element with an appropriate key and display it in a table with two columns: ID and Value. By the end of this lab, you will gain a better understanding of how to use React to create dynamic and responsive tables.

Data Table

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

Create a table element with two columns, ID and Value, where each row is generated dynamically from an array of primitive values.

To accomplish this, use the Array.prototype.map() method to create a new array of JSX elements representing each item in the input data array as a <tr> element with an appropriate key. Within each <tr>, add two <td> elements to display the row's index and value respectively.

Here's an example implementation:

const DataTable = ({ data }) => {
  return (
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Value</th>
        </tr>
      </thead>
      <tbody>
        {data.map((val, i) => (
          <tr key={`${i}_${val}`}>
            <td>{i}</td>
            <td>{val}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};
Enter fullscreen mode Exit fullscreen mode

To use this component with an array of people's names, for example, you can call it as follows:

const people = ["John", "Jesse"];
ReactDOM.createRoot(document.getElementById("root")).render(
  <DataTable data={people} />
);
Enter fullscreen mode Exit fullscreen mode

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Data Table lab. You can practice more labs in LabEx to improve your skills.


🚀 Practice Now: Dynamic React Table with Primitive Data


Want to Learn More?

Top comments (0)