0

I am working on Nextjs/Reactjs i am fetching data after click on button but in my console i am getting following error

Each child in a list should have a unique "key" prop

Here is my current code ( data is displaying with id and title)(

<button onClick={fetchReviewsFromServer}>Load Reviews From Server</button>
                        {
                            reviewfromserver.map(reviewnew=>{
                                return(
                                    <>
                                       <div key={reviewnew.id}> // not working
                                            <div>{reviewnew.id}- {reviewnew.title} </div>
                                       </div>

                                    </>
                                )
                            })
                        }
  • Since you just have 1 node, you do not have to wrap it in Fragment`<>>` – Rajesh Jan 05 '23 at 11:22
  • It needs to be on the **outermost** tag, in this case that's the fragment. However, in this case you don't need the fragment since there's only one child, so you can remove the fragment. If you wanted to use the fragment cos you're adding more children later for example, replace the empty tag fragment with `` – Jayce444 Jan 05 '23 at 11:23
  • Have a look at the answer here: https://stackoverflow.com/a/43892905/4989208 to understand more about the key prop. Try removing the fragment wrapping your component, and ensure that the ids are unique for all the elements in the array. – Swanky Coder Jan 05 '23 at 11:28

2 Answers2

2

The child in your list is the empty <> element, I don't see a need for it regardless, since you only have one child element to that element.

<button onClick={fetchReviewsFromServer}>Load Reviews From Server</button>
{
    reviewfromserver.map(reviewnew=>{
        return(
            <div key={reviewnew.id}> // not working
                <div>{reviewnew.id}- {reviewnew.title} </div>
            </div>
        )
    })
}
Nora Söderlund
  • 1,148
  • 2
  • 18
  • 1
    While not necessary here, If OP did need to use a fragment as the outer element, they would have to avoid the shorthand `<>...>` and instead use the longhand equivalent `...` in order to supply it with a `key` prop. – spender Jan 05 '23 at 11:28
  • @Nora Soderlund : i have to remove<>> because right now i have one child element otherwise code is okay/fine , am i right ? –  Jan 05 '23 at 11:31
  • 1
    Kind of? The issue is that you're not setting the key property as the outer element's property. **Removing the fragment element does resolve it, yes,** because then the outer element (the list child) becomes your `div`. – Nora Söderlund Jan 05 '23 at 11:34
0

That's because the fragmets are items. Remove them, you don't need them anyway.

Čedomir Babić
  • 522
  • 4
  • 12