Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to display some data received through API to table in React Js, data is received as object so I can't map trough it. What would be the best practice in this situation? For now the data is hardcoded, but it needs to be dynamic.

My code in CodeSandbox

export default function App() {

  const data ={
    
    "people" :[
      {
        "name":"John",
        "last_name":"Doe",
        "age":"25",
        "Occupation":"driver",
      },
      {
        "name":"Jack",
        "last_name":"Brown",
        "age":"24",
        "Occupation":"it"
      },
      {
        "name":"Oliver",
        "last_name":"Black",

        "age":"30",
        "Occupation":"cto"
      },
    ],

    "format":{"last_name":"Last Name"}
  }
  
  return (
    <div className="App">
     <table>
       <tbody>
         <tr>
           <td>Name</td>
           <td>John</td>
           <td>Jack</td>
           <td>Oliver</td>
           
         </tr>
         <tr>
           <td>Last Name</td>
           <td>Doe</td>
           <td>Brown</td>
           <td>Black</td>
           
         </tr>
         <tr>
           <td>Age</td>
           <td>25</td>
           <td>24</td>
           <td>30</td>
           
         </tr>
         <tr>
           <td>Occupation</td>
           <td>driver</td>
           <td>it</td>
           <td>ceo</td>
         </tr>

         
       </tbody>
     </table>
    </div>
  );
}


needs to be displayed as

Name         John     Jack      Oliver
Last Name    Doe      Brown     Black
Age          25       24        30
Occupation   driver   it        ceo

I can't figure out how to display the data dynamically ( and also add data from format part. I would appreciate any suggestion and help, thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

See if this works! https://stackblitz.com/edit/react-ie2rt6

import React from "react";

const Table = ({ headers, data }) => {
  return (
    <div>
      <table>
        <thead>
          <tr>
            {headers.map(head => (
              <th>{head}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map(row => (
            <tr>
              {headers.map(head => (
                <td>{row[head]}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default Table;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...