Home > Mobile >  how to sync table header with its body
how to sync table header with its body

Time:10-19

header titles looks like: ['name', 'lastname', 'age'] and the body looks like: ['lastnameText', 15, 'nameText'], its order may be different from titles list

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

the result looks like this way:

   name       lastname   age
lastnametext     15      name

How can I explicitly sync the titles with the content?

CodePudding user response:

Edited this answer and found a solution for what you want. See this code.

So what I do is sorting the content I get before displaying it:

  const allSortedContent = []; 

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

Here I go through the content array which contains rows as objects. For each row - I sort the fields of it to be according the order of the headers. In each iteration, I use the sortedRowValues array that will contain the <td> elements of this row (according to the headers order).

After finishing each row, I push the mapped row - (sortedRowValues) to the allSortedContent array which contains all the sorted rows.

Lastly, in the table body, I simply return the allSortedContent.

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

And the data structure you send through props should be in this structure, but it's completely okay if it's out of order:

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

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

CodePudding user response:

i think it'll solve your problem because you have a array and you want to write keys in head and write items in body. I assumed like this.

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