2

When I try to iterate through my variable badges and display each badge, I get this error :

Each child in an array or iterator should have a unique "key" prop.

    var badges = author.badges.map((badge, index) => <span className="author__badge">
                                                        <Icon key={"icon" + index} name={`icon-${badge}`} />
                                                       </span>;
                                  );
      return (

          <span className="author__name">{author.name}</span>

            { author.badge === "" ||
                badges
            }
            <span className="author__nickname">{author.nickname}</span>
          </div>
      );
Orsay
  • 1,080
  • 2
  • 12
  • 32
  • check this out https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js – Jayavel Mar 31 '18 at 08:45
  • 1
    Possible duplicate of [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – Matt Way Mar 31 '18 at 08:46
  • Yes sorry I know. I already saw the related questions but still have the same error. So I wonder if it doesn't come to somewhere else – Orsay Mar 31 '18 at 08:49

2 Answers2

1

As mentioned in React Documentation :

A good rule of thumb is that elements inside the map() call need keys.

You need to make use of key={ } and give it any unique value

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort

So in your case one of the ways (You can amend it accordingly):

var badges = author.badges.map((badge, index) => 
              <span className="author__badge" key={index}>);
Community
  • 1
  • 1
Aaqib
  • 9,942
  • 4
  • 21
  • 30
0

Just move the key from Icon to the tag including the two spans outside the array.

var badges = author.badges.map((badge, index) => <span className="author__badge">
                                                    <Icon key={author.name + "icon" + index} name={`icon-${badge}`} />
                                                   </span>;
                              );
  return (
      <div> // This was missing
      <span key={author.name} className="author__name">{author.name}</span>

        { author.badge === "" ||
            badges
        }
        <span key= {"nick" + author.name}className="author__nickname">{author.nickname}</span>
      </div>
  );

Or something similar. It this component is used in and array maybe a key will be needed for the div also.

madlers
  • 111
  • 4