Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  38] [ 3]  / answers: 1 / hits: 11058  / 4 Years ago, mon, may 18, 2020, 12:00:00

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.


More From » reactjs

 Answers
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.


[#3775] Friday, May 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josuea

Total Points: 609
Total Questions: 121
Total Answers: 104

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
josuea questions
Tue, Mar 2, 21, 00:00, 3 Years ago
Fri, Apr 17, 20, 00:00, 4 Years ago
Fri, Sep 27, 19, 00:00, 5 Years ago
Sat, Jun 8, 19, 00:00, 5 Years ago
;