0

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>
)
1
  • You can use CSS to add content before or after element Commented Aug 25, 2020 at 8:38

1 Answer 1

2

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>

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

2 Comments

That is exactly I just commented under answer
Lol, we thought the same thing

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.