i don't know why react keep asking for the key even when the key is added.

i have a component that render some posts but each posts is rendered in it's own component and it's inside a component that come from Swiper

my component look like this:

export default function Posts() {

const postsCards = posts.map(post => {
   return <SwiperSlide className="w-25" key={post._id}>
              <PostCard post={post} key={post._id}/>
          </SwiperSlide>
})

return (
<div className="container">
    <h4>Top posts</h4>
    <Swiper
      slidesPerView= 'auto'
      spaceBetween= {10}
      observer= {true}
      observeParents={true}
    >
        {postsCards}
    </Swiper>
</div>
)
}
4

There are 4 answers

0
Someone Special On

This is not exactly a solution, but using the index as a key for now, allows you to identify whether your post._id is unique.

const postsCards = posts.map((post, index) => {
   return <SwiperSlide className="w-25" key={`${post._id}-${index}`}>
              <PostCard post={post}/>
          </SwiperSlide>
})

If it's no longer returning error with the above codes, then it's likely you have duplicated posts in your posts array.

1
user9779830 On

As I can see, you have the same key for a SwiperSlide and for a PostCard too. You should have a unique key for each of them.

0
Javvy7 On

Adding the key attribute to just the Parent component SwiperSlide would be enough.

3
Pranava Mohan On

As mentioned by @user9779830

The SwiperSlide and PostCard have same key. I have created a solution where the key of PostCard component is set to the hash of post._id:

hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)

export default function Posts() {

const postsCards = posts.map(post => {
   return <SwiperSlide className="w-25" key={post._id}>
              <PostCard post={post} key={hashCode(post._id.toString())}/>
          </SwiperSlide>
})

return (
<div className="container">
    <h4>Top posts</h4>
    <Swiper
      slidesPerView= 'auto'
      spaceBetween= {10}
      observer= {true}
      observeParents={true}
    >
        {postsCards}
    </Swiper>
</div>
)
}

As you can see, the key for both of the components will be different as the PostCard component uses the hash of 'post._id'