Reputation: 9125
Is there any simple way of removing the trailing comma in the below snippet
const renderElements = () => {
if (!(data && data.length)) return [];
return data.map(({ id, name }, index) => (
<p key={id}>{`${name}${
!(index === data.length - 1) ? "," : ""
}`}</p>
));
}
return (
<div>
{renderElements()}
</div>
)
Upvotes: 0
Views: 298
Reputation: 20824
Your code works fine, so why bother to find another way to write it?
But perhaps, you don't need to insert the comma manually, just leave it to css:
const renderElements = () => {
if (!(data && data.length)) return [];
return data.map(({ id, name }) => (
<p key={id}>{name}</p>
));
}
return (
<div>
{renderElements()}
</div>
);
div p {
display: inline;
}
div p:not(:last-of-type)::after {
content: ',';
}
<div>
<p>Alice</p>
<p>Bob</p>
<p>Charlie</p>
<p>David</p>
</div>
Upvotes: 2