Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Display Multi-dimensional Array Data in React

This guide covers how to create and display data using a two-dimensional array in React.

Oct 29, 2020 • 6 Minute Read

Introduction

Arrays are one of the most efficient and widely used data structures in programming languages to store data in a linear order. Array data can be accessed using a numeric index in sequential order, starting from zero. Often, real-world data is stored in tables via rows and columns. A table can easily be stored using a two-dimensional array in which each element of the container array is also an array:

      let cart =[
	["Corn", "Potato", "Radish"],
	["Tomato", "Graphes", "Mango"],
];
    

Two-dimensional arrays are quite useful to store tabular data or develop 2D games, graphics, and solutions for an algorithmic problem using an adjacency matrix. Two-dimensional arrays or objects can easily be integrated with JSX to create UI at runtime in React. This guide covers the details of various techniques to create and display data using a two-dimensional array in React.

Create a Two-dimensional Array

A two-dimensional array can be created using pairs of square brackets [[],[]] or using the Array class:

      let board = Array(2).fill(0).map(row => new Array(3).fill(1))
// [[1,1,1], [1,1,1]]
    

The array fill method is quite helpful in creating an array object with a predefined value. The above snippet will create an array of length two, fill it with zeros, and replace every element with another array of three elements.

Display Two Dimensional Data Using Lists

HTML ordered and unordered lists are often used to display lists using bullets characters or sequential order numbers or letters. Arrays can be traversed using for loops, but this can also be done using a functional approach via the map method to process the array elements. The map method offers a convenient way to apply the transformation function on each element of an array in a much cleaner way. A two-dimensional list can be transformed into an HTML element using two map operations:

      import React from "react";

export default function App() {
  const cart = [
    ["Corn", "Potato", "Radish"],
    ["Tomato", "Graphes", "Mango"],
  ];
  return (
    <div>
      {cart.map((items, index) => {
        return (
          <ol>
            {items.map((subItems, sIndex) => {
              return <li> {subItems} </li>;
            })}
          </ol>
        );
      })}
    </div>
  );
}
    

The above snippet goes through the items to create an ol element that displays the subItem bullet list. The JavaScript code is executed inside the curly braces (JSX) to create and display the elements inside the render method.

Display Two-dimensional Data in a Table

The HTML table element can also be used to display two-dimensional data in a tabular form using the tr, td, and th elements. The th tag is used for the heading elements, with bold and center text style. The td tag is used to define the table data. The table elements can be constructed at run time in JSX using map:

      import React from "react";
import "./style.css";

export default function App() {
  const students = [
    ["Name", "Subject", "Marks"],
    ["ABC", "Arts", 80],
    ["XYZ", "Science", "70"],
  ];
  return (
    <div>
      <table>
        <thead>
          <tr>
            {students[0].map((item, index) => {
              return <th>{item}</th>;
            })}
          </tr>
        </thead>
        <tbody>
          {students.slice(1, students.length).map((item, index) => {
            return (
              <tr>
                <td>{item[0]}</td>
                <td>{item[1]}</td>
                <td>{item[2]}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
    

The first row is used to display the headings. The rest of the rows are extracted using slice and traversed using the map function to create an array of data elements using tr and td.

Fix Missing Key Error

The above code works fine, but it produces a warning to use a key-value for the dynamically generated row elements. React uses a virtual DOM to track the changes in the page elements instead of applying the changes directly to the actual DOM. The virtual DOM is used to apply the new changes in the actual DOM using a diffing algorithm with a unique value (key) to identify the modifications in the virtual DOM elements. So, modify the code to use index or unique element data values as key:

      <table>
  <thead>
    <tr>
      {students[0].map((item, index) => {
        return <th key={index}>{item}</th>;
      })}
    </tr>
  </thead>
  <tbody>
    {students.slice(1, students.length).map((item, index) => {
      return (
        <tr key={index}>
          <td key={item[0]}>{item[0]}</td>
          <td key={item[1]}>{item[1]}</td>
          <td key={item[2]}>{item[2]}</td>
        </tr>
      );
    })}
  </tbody>
</table>;
    

Note: For changes to dynamic data, always use unique values from data instead of an index to avoid unexpected rendering issues.

Tips

• To support complex hierarchies, use third-party grid libraries. • Use Array to define array containers with defined length, though always prefer the use of an array literal ([]).

Conclusion

Element generation is extensively used in React and JSX to generate elements at run time. Array or array literal ([]) supports a variety of functions to traverse data that can be displayed using HTML elements. If there is no unique value that can be used as a key, then you can use an index as a key if the data is static and never reordered. Otherwise, you can use computed hash values of data or generate random or sequential unique keys. Use HTML tables if the data is static as it's easy to modify the custom structure and apply CSS. Happy coding!