'How to eliminate empty node with loop inside React JSX
how right to filter data from an object and then render it? I found a suitable working solution, but the problem is that I have to return an empty node, otherwise I will get an error: ``` Array.prototype.map() expects a value to be returned at the end of arrow function:
const movieRows = Object.entries(movieObject).map(([key, value], id) => {
if (
key === "Actors" ||
key === "Director" ||
key === "Country" ||
key === "Runtime"
) {
return (
<tr key={id}>
<td className="title">{`${key}:`}</td>
<td className="value">{`${value}`}</td>
</tr>
);
} else {
// this
return <></>;
}
});
Even that is not quite good, because I get a message to the console that it is necessary to add a key.
So I'm returning an unnecessarily empty node, just to satisfy React.
else {
return <tr key={id}></tr>;
}
Is there any way to write this without an unnecessary node?
Thanks
Solution 1:[1]
Thanks to Nick, the solution is:
const movieRows = Object.entries(movieObject)
.filter(
([key]) =>
key === "Actors" ||
key === "Director" ||
key === "Country" ||
key === "Runtime"
)
.map(([key, value], id) => {
return (
<tr key={id}>
<td className="movie-subtitle">{`${key}:`}</td>
<td>{`${value}`}</td>
</tr>
);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick Parsons |
