简体   繁体   中英

Rendering React components inside another div

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>)
})

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>)
})

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>
        )
    })

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM