4

I have a react component that is rendering some results. The problem I am having is with result.participants. This is an array, so map is rendering both names without any spacing and I am finding it difficult to get those spaces inserted.

The result.participants is an array of strings.

How do I insert a space or some logic to put in a comma and a space if the length is >1 ?

render: function(){
  return (
  <ul>
    {
      this.state.pads.map(function(result){
        return [
        <a href={result.pageUrl}>{result.title}</a>,
        <li key={result.participants}>Participants: {result.participants} </li>,
        <li key={result.summary}>Summary: {result.summary}</li>,
        <li key={result.lastEdit}>Last Edited: {new Date(result.lastEdit).toDateString()} </li>,
        <p></p>
        ];
      })}
  </ul>
)
}
1
  • 1
    According to HTML standard, you don't suppose to have <p> and <a> directly inside <ul>. Commented Sep 4, 2014 at 20:53

2 Answers 2

4

And if you don't care about wrapping each participant in a <span>, you could simply use the built-in Array.prototype.join method:

<li key={result.participants}>Participants: {result.participants.join(', ')} </li>,

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

Comments

3

Like a commenter mentioned, you should not put bare <a> and <p> tags into a <ul> directly. But that is beside the point, this question is about array handling in React.

You should be able to use a control flow structure nested in JSX like this:

{
  result.participants.map(function(participant, idx) {
    if (idx == result.participants.length - 1) {
      return (
        <span>{participant}, </span>
      );
    } else {
      return participant;
    }
  })
}

1 Comment

you could alternatively do function(participant, idx, array){ if (idx === array.length) .... I prefer it because you can then extract that function and use it in multiple contexts without changing anything.

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.