David W
David W

Reputation: 25

React: Each child in a list should have a unique "key" prop persists with unique keys

I'm getting the react error for not passing a unique key to a rendered list.

As far as I can tell, I'm passing a unique key to the outer-level element within the list, so if anyone can identify what the issue is and how to fix it I'd appreciate it.

I suspect it might be the way I'm returning the list. The original array has an empty obj inserted in at pos 1, then when I map over the array I return a component Feed at index 1, and return the original items otherwise. Would the two returns be the issue here?

Any help is greatly appreciated.

import { useEffect } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

import { fetchStories } from '../actions/index';
import Snippets from './Snippets';




const Stories = ({ stories, fetchStories }) => {

  useEffect(() => {
    fetchStories();
  }, [fetchStories]);

  const emptyObj = {};

  //creates a new array with empy obj at pos 1, when mapping this we'll insert the Feed component at pos 1
  const storiesArrayWithFeed = () => {

    const copyStories = [...stories];
    copyStories.splice(1, 0, emptyObj);
    return copyStories
  }

  //renders the array of user stories into grid items, but inserts feed component into position 1 in index 
  const renderGrid = () => {
    const storiesWithFeed = storiesArrayWithFeed();
    return storiesWithFeed.map((story, index) => {
      if (index === 1) {
        return (
          <div className={`stories-grid-item story-item `} key={index}>
            <Snippets />
          </div>
        )
      } else {
        return (
          <div className={`stories-grid-item story-item`} key={story._id}>
            <Link
              to={`/stories/${story._id}`}
            >
              <h3>{story.title}</h3>
              <p dangerouslySetInnerHTML={{ __html: `${story.sanitizedHtml}` }}
                className="story-page-story">
              </p>
            </Link>
          </div>
        )
      }
    })
  }





  return (
    <div className="stories-container">
      <h1>Latest Stories</h1>
      <div className="stories-grid author-stories-grid">
        {renderGrid()}
      </div>
    </div>
  )
}


const mapStateToProps = ({ stories }) => {
  return { stories }
}

export default connect(mapStateToProps, { fetchStories })(Stories);

Upvotes: 0

Views: 101

Answers (1)

crispengari
crispengari

Reputation: 9333

Change this from

<div className={`stories-grid-item story-item`} key={story._id}> 

to

<div className={`stories-grid-item story-item`} key={index}> 

Goof luck, let me know if it works

Upvotes: 1

Related Questions