0

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>;
}
1
  • prods is an array, prods.id, prods.name, etc... are all undefined since those properties do not exist on type Array . Commented Apr 14, 2022 at 17:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>;
}

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.