N P
N P

Reputation: 2619

React error when using map

I am using map in my react component to loop over a list. It works fine when I have one link inside the map loop however my second link returns an error when I try to create an optimized build for it. Intellij gives me an error saying after my <a it expects either a ',' or a ')'. I can't see that I've missed a bracket or anything.

{this.state.players.map(singlePlayer =>
       <Link to={'edit-player/' + singlePlayer.id}><li key={singlePlayer.id}>{singlePlayer.name}</li></Link>
       <a id={singlePlayer.id} onClick={this.handleDelete.bind(this)}>delete</a>
                                    )}

Upvotes: 0

Views: 75

Answers (2)

Yashika Garg
Yashika Garg

Reputation: 2366

map should return only one element. So your code should be

{
  this.state.players.map((singlePlayer) => (
    <div>
      <Link to={"edit-player/" + singlePlayer.id}>
        <li key={singlePlayer.id}>{singlePlayer.name}</li>
      </Link>
      <a id={singlePlayer.id} onClick={this.handleDelete.bind(this)}>
        delete
      </a>
    </div>
  ));
}

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104359

Issue is, you are returning more than one item inside the map, you can't return more than one element, so you need to wrap the Link and a by either div or li or by any other element. try this:

{
  this.state.players.map((singlePlayer) => (
    <div>
      <Link to={"edit-player/" + singlePlayer.id}>
        <li key={singlePlayer.id}>{singlePlayer.name}</li>
      </Link>
      <a id={singlePlayer.id} onClick={this.handleDelete.bind(this)}>
        delete
      </a>
    </div>
  ));
}

Upvotes: 0

Related Questions