3

I am calling an API endpoint, saving it's data to a state and then rendering it. It's displaying in the browser but there is a warning on the console: Warning: Each child in a list should have a unique "key" prop..

My app.js:

class App extends Component {
  render () {
    return (
      <div>
        <Profile profiles={this.state.profile} />
      </div>
   )
  }
  state = {
    profile: []
  };

  componentDidMount() {
    fetch('http://127.0.0.1:8000/profiles')
    .then(res => res.json())
    .then((data) => {
      this.setState({ profile : data })
    })
    .catch(console.log)
  }
}
export default App;

I don't understand where do I put the key prop in render(). This is my snippet profile.js:

const Profile = ({ profiles }) => {
  return (
    <div>
      <center><h1>Profiles List</h1></center>
      {profiles.map((profile) => (
        <div className="card">
          <div className="card-body">
            <h5 className="card-title">{profile.first_name} {profile.last_name}</h5>
            <h6 className="card-subtitle mb-2 text-muted">{profile.dob}</h6>
            <p className="card-text">{profile.sex}</p>
          </div>
        </div>
      ))};
    </div>
  )
};

export default Profile;

What improvement do the key prop brings over not using it? I am getting overwhelmed with these <div>...</div> tags.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
forest
  • 1,312
  • 3
  • 20
  • 47

2 Answers2

5

If you use map in your JSX return then you need to provide the parent element with the key prop so that it's uniquely identified.

https://reactjs.org/docs/lists-and-keys.html

You would preferably use an object ID but if you know a field (or combinations of fields) that would constitute a unique key then you could use that instead:

{profiles.map((profile) => (
  <div 
    key={'profileList_'+profile.first_name+profile.last_name} 
    className="card"
  >
    ...
  </div>
)};

NOTE: In the example I used profileList_ as a prefix just in case you need to use the same unique identifier (object ID or in this case profile.list_name+profile.last_name) as a key somewhere else in a different context.

bilwit
  • 799
  • 1
  • 5
  • 9
3

you have to set uniq value to key props to the first div inside map

{profiles.map((profile) => (
        <div key={profile.id} className="card">

read the doc

IT's Bruise
  • 824
  • 5
  • 11