1

I've been getting a "Each child in a list should have a unique key prop" error. I've read up on the documentation and put keys in, but no luck. Not sure what I'm misunderstanding!

blogPosts is imported from a context. The ids being called as keys are unique (POSTID1, POSTID2, ...etc). Got rid of some classnames for better readability.

const topicPosts = blogPosts.filter((post)=>post.topic.toLowerCase()===topic);
const handleLoadMore = () => {
  const newIndex = articleIndex + 5 > topicPosts.length ? topicPosts.length : articleIndex + 5;
  setArticleIndex(newIndex);
}
return (
  <section onClick={handleOutsideClick}>
    <div>
      <section>
        <h1>{topic}</h1>
        {
          topicsData.map((topicData)=> topicData.name.toLowerCase()===topic && <p key={topicData.id}>{topicData.intro}</p>)
        }
      </section>
      <div>
        <section>
          <div>
            {
              topicPosts.slice(0,3).map((post)=>{
                const { id } = post;
                return (
                  <TopicPagePost key={id} {...post}/>
                )
              })
            }
          </div>
          <div className={topicPosts.length>3 ? `subpage-articles` : `display-none`}>
            {
              topicPosts.slice(3,articleIndex).map((post, index)=>{
                const { id } = post;
                return (
                  <>
                    <TopicPagePost key={id} {...post}/>
                    {
                      index%4===0 && <div key={index} className="subpage-main-ad">
                        Ad placement here
                      </div>
                    }
                  </>
                )
              })
            }
          </div>
          <button type="button" onClick={handleLoadMore}>Load more articles</button>
        </section>
        <aside>
          <SubscribeBlock/>
          <div>
            Ad placement here
          </div>
        </aside>
      </div>
    </div>
  </section>
)
kev23
  • 13
  • 2
  • Does this answer your question? [Can I add a key prop to a React fragment?](https://stackoverflow.com/questions/59390955/can-i-add-a-key-prop-to-a-react-fragment) – Martin Mar 21 '21 at 17:08

1 Answers1

1

That is because you need to add a key to the first element returned from the map, in this case <>.

To do that, you need to replace <> with a <Fragment> instead, so you can add a key directly to it:

import React, { Fragment } from "react"
{topicPosts.slice(3,articleIndex).map((post, index) => {
  const { id } = post;
    
  return (
    <Fragment key={id}>
      <TopicPagePost {...post}/>

      {index%4===0 && (
        <div className="subpage-main-ad">
          Ad placement here
        </div>
      )}
    </Fragment>
  )
})}
ale917k
  • 1,494
  • 7
  • 18
  • 37