What is the best way to align table headers with their respective content?

Ensuring proper alignment of table columns with their respective headers is crucial. Consider an array of headers:

const titles = ['name', 'lastname', 'age']

When displaying the table, the content may be like this:

const content = ['lastnameText', 15, 'nameText']

The challenge lies in the fact that the order of items in the content array doesn't always match the order of headers.

<table>
  <thead>
    {titles.map(item => (
      <tr>{item}</tr>
    ))}
  </thead>
  <tbody>
    {content.map(item => (
      <tr>{item}</tr>
    ))}
  </tbody>
</table>

Upon rendering, the current result may show the following layout:

   name       lastname     age
lastnametext     15      nametext

As you can see, the header columns are not correctly aligned. The desired output should resemble this:

   name      lastname     age
 nameText  lastnametext   15

Answer №1

After revising this response, I have come up with a solution to address your needs. Take a look at this code.

*Note: If the fields of all rows in your content are in the correct order, and only the headers' arrangement is causing issues - this code should suffice.


In order to make it function as a reusable table, capable of handling situations where the content order is jumbled up, I implement a sorting mechanism for the content data before rendering:

  const allSortedContent = []; 

  for (const row in props.content) {
    const sortedRowValues = []; 
    // Sorting the values of each row according to the header order.
    props.headers.forEach((header) => {
      const value = props.content[row][header];
      sortedRowValues.push(<td>{value}</td>);
    });
    allSortedContent.push(<tr>{sortedRowValues}</tr>);
  }

This code snippet processes the array content consisting of row objects. For every row, I rearrange the fields to align with the header sequence. At each step, I utilize the sortedRowValues array to store the <td> elements of the current row (matching the headers' order).

Upon completing each row, I add the mapped row (sortedRowValues) to the allSortedContent array which holds all the sorted rows.

Lastly, within the table body section, I simply display the allSortedContent.

return (
    <div>
      <table>
        <thead>
          <tr>
            {props.headers.map((item) => (
              <td>{item}</td>
            ))}
          </tr>
        </thead>
        <tbody>{allSortedContent}</tbody>
      </table>
    </div>
  );

The data structure passed through props must adhere to this format, but disorder is acceptable:

const headers = ['age', 'lastName', 'name'];

const content = [
    { name: 'Jule', lastName: 'Abc', age: '24' },
    { lastName: 'Park', age: '32', name: 'Josh' },
  ];

Answer №2

This solution should resolve your issue as you have an array and want to display keys in the header and items in the body. The assumption made is outlined below.

<table>
  <thead>
    {Object.keys(contents).map((key) => {
        <tr>{key}</tr>
    })}
  </thead>
  <tbody>
    {contents.map(item => (
      <tr>{item}</tr>
    ))}
  </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is CSS causing a overflow when trying to print 210mm by 297mm on A4?

Take a look at this basic HTML code : <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <style type="text/css"> .page { width: 200px; height: 500px; background ...

Linking promises together ensures that they always resolve with a result

My understanding of how to chain promises is still not completely solid. What I am trying to achieve is as follows: I have a promise that can either resolve or reject. The following code checks for this and continues if the promise resolves, or stops if i ...

React: Unable to access the 'getWeather' property due to it being undefined

I'm currently stuck trying to identify the source of a type error in my React code, but it's eluding me at the moment. It's possible that I'm overlooking a key concept of React. Within my React application, I have a Weather class defin ...

Managing API responses using Redux and Typescript

As a beginner in Typescript, I am struggling to integrate Redux with it. The documentation on using Redux with Typescript is confusing me. I am attempting to fetch data and dispatch it to my reducer for future use, just as I did before adopting Typescript ...

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...

Troubleshooting Vue component data management issues

I'm perplexed as to why the data is coming up as undefined even though I am passing the correct property from the component. Here is my Vue component: Vue.component('store-squaretile-component',{ template: '#store-squaretile-compon ...

hide content on both desktop and mobile devices

I can't seem to figure out what's wrong here and my mind is blank. I have 2 tables - one for desktop users and one for mobile users. I attempted to hide one using the display none property in my code. .mobile{display: none;} This CSS was mean ...

An error occurred with redirecting using jQuery Mobile's new method in version 1.5

Utilizing jQuery Mobile for its history state feature, I am looking to redirect users to another "page" using the jQuery method recommended in their latest documentation. p/s: I prefer the jQuery navigation method due to the hashchange/history support and ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

Arrange Bootstrap Checkboxes in a horizontal layout instead of a vertical one

Excuse my lack of experience as I am just starting out. I need help in arranging the checkboxes on my website to be aligned horizontally instead of vertically. Even though they are within a row div, they still stack on top of each other. Here is the code ...

What could be causing this code to keep looping?

This is my submission for a class project. The task given was: "Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a num ...

Elevate a div above the rest when it is selected or dragged

I am facing an issue with draggable divs inside a parent container. Each div has a popup edit panel to modify its content. The problem arises when the divs overlap, causing the edit panel to get hidden behind another div. I want to ensure that whenever a d ...

Troubleshooting Django's iteration error

Hey there! I'm currently a student, so please bear with me if my code isn't perfect yet. I'm working on a project that involves creating an online webshop. The database and email system are already set up, but I'm having trouble specify ...

Change the background color of a div element dynamically

Is there a way to dynamically apply a background color to only the first 5 div blocks in React? Here is my code snippet: const ImageBlock = ({block}) => { const number = 5 return ( <React.Fragment> {block.map((item, index) => ...

What is the best way to compress all folders, including the main directory?

I am working on a PHP script where I need to zip all directories, including the root directory. For instance, if my script file is located at /practice/zip/index.php, and I want to create a zip archive for the entire /practice directory. Currently, my sc ...

React Native - Implementing a dynamic form that adapts based on the answer given by its parent

My JavaScript Object has a simple state structure as follows: pertanyaan: [{ label: "label1", type: 'dropdown', key: 'keyFoo1', option: [{ value: "foo1" }, { value: "foo2", additional ...

Using Vue.js to showcase Unicode, hexadecimal emojis, and octal literals in HTML

Received this response from the webserver: "\ud83d\ude48\ud83d\ude02\ud83d\ude30\ud83d\ude09\ud83d\udc4f\ud83c\udffd\ud83d\udc4c\ud83c\udffd\ud83d\udd1d\u2714&b ...

Is it possible to manipulate an image tag's image using only CSS?

Is it possible to hide an image from the src attribute of an <img> tag and instead set a background image on the tag using CSS? One idea could be adjusting the positioning or text-indent of the actual image to move it out of view, and then applying ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...