Zena Mesfin Zena Mesfin - 3 years ago 145
React JSX Question

Codition on a last iteration of loop in React JSX?

I have a list of emails I need to loop through and display in this format.

renderEmaillist() {
return this.props.OfficeEmailAddress.map((officeEmail) => {
return (
<a key={emailID} href={`mailto:${officeEmail}`}>{officeEmail}{'; '}</a>

When its rendered

email@mail.com; email2@mail.com;

I want to remove the semicolon at the end of the last loop only.

What is the bets way to do this?

Answer Source

You have access to the index and the full array from within map:

return this.props.OfficeEmailAddress.map((officeEmail, index, arr) => {
    return (
      <a key={emailID} href={`mailto:${officeEmail}`}>{officeEmail}{index === arr.length - 1 ? '' : '; '}</a>

I added a ternary to determine if we are on the last element of the array and, if we are, to just output an empty string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download