'How to create dynamic Header from API React table

How can I create a header for my react table based on the API response?

for example the data I don't want to define columns manually for the table, so how can I create the headers dynamically from the keys of the object

let testData = [

{
  "id": "1",

  "name": "test",
  "namespace": "test",
  "description": "test",
},
{
  "id": "2",
  "name": "test2",
  "namespace": "test2",
  "description": "test2",
} ]


Solution 1:[1]

Normally, you would like to make the table header static, because you can not control what's returning the endpoint. An approach to this might be this one:

const App = () => {
  let testData = [

    {
      "id": "1",
    
      "name": "test",
      "namespace": "test",
      "description": "test",
    },
    {
      "id": "2",
      "name": "test2",
      "namespace": "test2",
      "description": "test2",
    } ]

  let headers = Object.keys(testData[0]);
  return <table>
    <thead>
      <tr>
       {
         headers.map(header => {
          return <th>{header}</th>
        })
        }
      </tr>
    </thead>
    <tbody>
      { 
        testData.map(({id, name, namespace, description}) => {
          return <tr>
            <td>{id}</td>
            <td>{name}</td>
            <td>{namespace}</td>
            <td>{description}</td>
        </tr>
      })
      }
      
    </tbody>
  </table> 
}

You could also apply the same logic to avoid inserting the body manually.

Solution 2:[2]

I was able to come up with a solution for this

let testData = [

{
  "id": "1",

  "name": "test",
  "namespace": "test",
  "description": "test",
},
{
  "id": "2",
  "name": "test2",
  "namespace": "test2",
  "description": "test2",
} ]

//so define the columns

let columns = Object.keys(testData[0]).map(key =>{

return {
//set header and accessor

Header: key,
accessor: key

}

})

//then pass in data and columns variable to table component

  <Table data={tableData} columns={columns} />

this is how you create dynamic headers based on data instead of manually defining headers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Erick Villatoro
Solution 2 ido evergreen