Dynamic React Table with Primitive Data

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/list_keys("`Lists and Keys`") subgraph Lab Skills react/jsx -.-> lab-38348{{"`Dynamic React Table with Primitive Data`"}} react/list_keys -.-> lab-38348{{"`Dynamic React Table with Primitive Data`"}} end

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>
  );
};

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} />
);

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.

Other React Tutorials you may like