skip to Main Content

I want to display array of objects in 2 columns in a table. what is the easiest method to display the list as two columns?

const columns = [
    {
      subHeading: "A",
      subText: ["1", "2"]
    },
    {
      subHeading: "B",
      subText: ["3", "4"]
    },
    {
      subHeading: "C",
      subText: ["5", "6"]
    },
    {
      subHeading: "D",
      subText: ["7", "8"]
    }
  ];

Desired display on HTML Page:

A B
C D

2

Answers


  1. You can use Grid here as:

    CODESANDBOX

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr" }}>
      {columns.map((col, i) => {
        return <h1>{col.subHeading}</h1>;
      })}
    </div>
    
    Login or Signup to reply.
  2. Displaying content in 2 columns can be easily done with CSS-Grid by using display: grid; grid-template-columns: repeat(2, 1fr);. This is not an appropriate task for a table as it is not tabular data!

    Creating the content dynamically can be done by looping through the arrays and using createElement:

    const COLUMNS = [{
        subHeading: "A",
        subText: ["1", "2"]
      },
      {
        subHeading: "B",
        subText: ["3", "4"]
      },
      {
        subHeading: "C",
        subText: ["5", "6"]
      },
      {
        subHeading: "D",
        subText: ["7", "8"]
      }
    ];
    
    // EventListener to wait until the DOM is loaded
    window.addEventListener('DOMContentLoaded', printArray);
    
    // function to loop of the array and read every subHeading and subText
    function printArray() {
      COLUMNS.forEach(object => {
        createSection(object.subHeading, object.subText);
      })
    }
    
    
    // function to create new sections
    function createSection(heading, text) {
      // creates a new section
      let newSection = document.createElement('section');
      
      // adds the title to the section
      let newTitle = document.createElement('h2');
      newTitle.textContent = heading;
      newSection.appendChild(newTitle);
      
      // adds the text elements to the sections
      text.forEach(arrayElement => {
        let newParagraph = document.createElement('p');
        newParagraph.textContent = arrayElement;
        newSection.appendChild(newParagraph);
      });
      
      // appends the sections to the body
      document.body.appendChild(newSection);
    }
    body {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 1em;
    }

    I just added the elements to the body directly. You can add them into a container of you choice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search