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

What am I not understating about using Maps in React?

I am new to react however I have done this same(ish) thing multiple times, however, this time it is just not working – I am assuming there is something I am fundamentaily not understanding. Please help!

I have a good old table:

        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                <TableRowUser key={1} />
                <TableRowUser key={2} />
                <TableRowUser key={3} />              
            </tbody>
        </table>

And a row:

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

import React from 'react';

const TableRowUser = () => {
  return <tr>
      <td>TEST</td>
      <td>TEST</td>
  </tr>;
};

export default TableRowUser;

This works just as expected.

However, when I change from hard code to using a map – nothing is rendered:

...
            <tbody>
                {users.map(user => {
                    console.log(user.name);
                    <TableRowUser key={user.id} />
                })}
            </tbody>
...

I should note – my data is fine as this console log prints correctly.
Just no TableRowUser is returned.

This appears trivial – What am I missing?

>Solution :

The issue you are running into is how arrow functions work.

You can do:

() => value

for a quick way to return a value, but if you are putting a body on the code, you need to use the return keyword

() => { return value }

Thus, your code should be:

<tbody>
            {users.map(user => {
                console.log(user.name);
                return <TableRowUser key={user.id} />
            })}
        </tbody>

or just

<tbody>
            {users.map(user => <TableRowUser key={user.id} />)}
</tbody>
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