React JS Warning: Each child in a list should have a unique "key" prop - Solved

Sep 13, 2022 . Admin

I got following warning in my react js project:

Warning: Each child in a list should have a unique "key" prop.

Let me show you how to fix it and what i made change there.

Waring Code:

  {this.state.posts.map((post) => (
    <tr>
      <td>{post.id}</td>
      <td>{post.title}</td>
      <td>{post.body}</td>
      <td>
        <button className="btn btn-danger" onClick={(e) => this.deleteRow(post.id, e)}>Delete</button>
      </td>
    </tr>
  ))}

Solution:
<tr key={post.id}>
Solution Code:
<tbody>
  {this.state.posts.map((post) => (
    <tr key={post.id}>
      <td>{post.id}</td>
      <td>{post.title}</td>
      <td>{post.body}</td>
      <td>
        <button className="btn btn-danger" onClick={(e) => this.deleteRow(post.id, e)}>Delete</button>
      </td>
    </tr>
  ))}
</tbody>

I hope it can help you too...

#React JS