2

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",
} ]

see answer below

ido evergreen
  • 91
  • 3
  • 9

2 Answers2

0

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.

Erick Villatoro
  • 170
  • 1
  • 9
0

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.

ido evergreen
  • 91
  • 3
  • 9