1

I was trying to get the object key of the array to display as the header of table but failed with using map in react. by using console.log, I was able to see it return the correct value it return blank on the HTML.

Here is my code

<tr>
{fileList.forEach((titleList) => {
      const title = [];
       title.push(Object.keys(titleList))
        // console.log(title) 
       title.map((item, key) => {
         // console.log(item)
           return <th key={key} scope="col">{item}</th>
        })
    })
}
</tr>

The json data was from here: https://jsonplaceholder.typicode.com/posts/1/comments Here is my full project code if you willing to check: https://codesandbox.io/s/dry-wave-gu0ns?file=/src/listPage/ListPage.js

Thanks!

1 Answer 1

2

What ever you do inside forEach will not go to your JSX, even if you are returning inside the map inside forEach.

Either move the entire code to another function or try the below approach

<tr>
{fileList.map((titleList) => {
      const titles = Object.keys(titleList);
        // console.log(title) 
       return titles.map((item, key) => {
         // console.log(item)
           return <th key={key} scope="col">{item}</th>
        })
    })
}
</tr>

this way what ever retuned from fileList.map is displayed in page.

Another approach using a funciton

function getHeaders(fileList) {
let headers = [];

fileList.forEach((titleList) => {
      const title = [];
       title.push(Object.keys(titleList))
        // console.log(title) 
       const head = title.map((item, key) => {
         // console.log(item)
           return <th key={key} scope="col">{item}</th>
        })
        headers = headers.concat(head);
    })
  }
  return headers;
}

And in your jsx use this

<tr>
   {getHeaders(fileList)}
</tr>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.