Create a table from JSON completely dynamically

I want to create entire table from a JSON array include dynamic ths, so a decoupled the head part to:

import React from 'react';
import TableDataTR from './TableTRView';
const TableView = ({ thds, tableData }) => {
    if (!thds) {
        return <table></table>;
    }
    return (
        <div>
            <table>
                <thead>
                    <tr>
                        {thds.map((data, i) => <th key={i}>{data.th}</th>)}
                    </tr>
                </thead>
                <TableDataTR tableData={tableData}/>
            </table>

        </div>
    )
}
export default TableView;

And the table prints the head part, but I am having trouble printing my tbody:

import React, { Component } from 'react';

class TableDataTR extends Component {
    render() {

       let rows = this.props.tableData.map((currElement, index) =>{
           return(
            <tr key={index}>
                <td>currElement[index]</td>
            </tr>
           ) 
       });


        return (
            <tbody>{rows}</tbody>
        );
      }
}
export default TableDataTR;

Example data, table head

thds : [ { th: 'th1' },
        { th: 'th2' }]

tableData:[ { tdData1: 'somedata', tdData2: 'somedata2' },
            { tdData1: 'somedata', tdData2: 'somedata2' },]

The table head works fine, but the data inside tbody is not displaying at all.

The final goal is to get any 2 arrays and display the table accordingly.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You need to access the table data using key name as

let rows = this.props.tableData.map((currElement, index) => {
      return (
      <tr>
          { Object.keys(currElement).map((item) =>
          (
            <td>{currElement[item]}</td>
     )
       )}
      </tr>   
      )
    });

Solution 2

There is a typo again in your <td>..</td> part, missing {} for your expression. For the dynamic solution after first map you need to map your Objects as well.

<tr key={index}>
    <td>
        {
            Object.keys(currElement).map(key => currElement[key])
        }
    </td>
</tr>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply