Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Table data is coming as empty in React

I am new to React. I am trying to create a table. I was able to fill table header but in table body i am not able to fill the rows and data.

This is actual data –

 const [batsmanAgainstTeamContent, setBatsmanAgainstTeamContent] = useState([
    {
      ball: "20",
      runsOffBat: "32.0",
      striker: "abc"
    },
    {
      ball: "38",
      runsOffBat: "68.0",
      striker: "xyz"
    },
  ]);

I think problem is in the below snippet –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const tdData =() => {
    return batsmanAgainstTeamContent.map((item) => {
      return (
        <tr>
          {
            Object.keys(item).forEach((key) => {
            return <td>{item[key]}</td>
          })
          }
        </tr>
      )
    })   }

In the following, ThData() works fine but tdData() does not –

`

return (
      <Container>
        <table className="table">
          <thead>
            <tr>{ThData()}</tr>
          </thead>
          <tbody>{tdData()}</tbody>
        </table>
      </Container>

edit: It works when using map instead of forEach

>Solution :

Here you need to use map instead of the forEach

    {
        Object.keys(item).map((key) => {
             return <td>{item[key]}</td>
        })
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading