In React is it ok to render another component inside a div like this? And does the key go on the div?
dataArray.map((data) => {
return (<div key = {data.id}>
<Person data = {data} />
</div>)
})
CodePudding user response:
Yes. Your approach is correct.
For this, each data object in your dataArray
must have a field called id
(or you could use some other UUID value).
Else, a simpler approach could be using the object index in the iterated array:
dataArray.map((data,id) => {
return (<div key = {id}>
<Person data = {data} />
</div>)
})
CodePudding user response:
Yes, this is the approach which is usually followed. However, you should always use key attribute or react will give warnings in the console.
You can do so considering the following :-
dataArray.map((data, index) => {
return (
<div key = {index}>
<Person data = {data} />
</div>
)
})
CodePudding user response:
If Person already returns jsx, then you can just do this if there is already an id in the data:
dataArray.map(data => <Person key={data.id} data={data} />)
If not, you can use Ankit Sanghvi's technique:
dataArray.map((data, idx) => <Person key={data.idx} data={data} />)
Doing it this way gets rid of the extra nesting divs. I sense from your example that you think you need divs just to hold the key in the map but you actually don't.