Home > Mobile >  How to fill in a table in react with an array of objects?
How to fill in a table in react with an array of objects?

Time:04-15

I have a pretty simple question, but couldnt deal with it yet. The first code works, while the second just give me empty table cells. What is the reason for that and how can I put data into table without assigning to anything?

const prods = [
    {id: 1, name: 'product1', cost: 100},
    {id: 2, name: 'product2', cost: 200},
    {id: 3, name: 'product3', cost: 300},
];

function App() {
    const rows = prods.map(function(item) {
        return <tr key={item.id}>
            <td>{item.name}</td>
            <td>{item.cost}</td>
        </tr>;
    });
    
    return <table>
        <tbody>
            {rows}
        </tbody>
    </table>;
}
const prods = [
    {id: 1, name: 'product1', cost: 100},
    {id: 2, name: 'product2', cost: 200},
    {id: 3, name: 'product3', cost: 300},
];

function App() {
    
    return <table>
        <tbody>
        <tr key={prods.id}>
            <td>{prods.name}</td>
            <td>{prods.cost}</td>
        </tr>;
        </tbody>
    </table>;
}

CodePudding user response:

You will see an empty row which may be invisible. But you can check it in browser dev tool.

Why? It's simple. You have not printed at all.

prods is an array. But in your render method (return <table> ...), you printed prods.name which is undefined.

So please change to see a row.

<td>prods[0].name</td>
...

Correct one is following:

function App() {

  return <table>
    <tbody>
    {prods.map(prod) => <tr key={prod.id}>
      <td>{prod.name}</td>
      <td>{prod.cost}</td>
      </tr>}
    </tbody>
  </table>;
}

CodePudding user response:

you are trying to access a property value of an object inside an array of object with out iterating it's items, which will result undefined. In your case, you need to map over your array of objects using the Map method, please refer to this url so you can get to know more about rendering multiple components using the map method in React.

  • Related