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:
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>