Home > Software engineering >  React.js warning when iterating a list with map()
React.js warning when iterating a list with map()

Time:12-09

I got this warning from web debug console:

react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop.

Check the render method of App. See https://reactjs.org/link/warning-keys for more information. at div at App (http://localhost:3000/static/js/bundle.js:31:80)

Below is my code:

import './App.css';
import {ethers} from "ethers";
import { useState } from 'react';
 

function App() {
  const [account, setAccount] = useState("")
  const [data, setData] = useState([])
  
  console.log(data);

  const connect = async () => {
    const provider = new ethers.providers.Web3Provider(window.ethereum)
    let res = await provider.send("eth_requestAccounts", []);
    setAccount(res[0]);
    getData(res[0]);
  }
  const getData = (_account) => {
    const options = {method: 'GET', headers: {accept: 'application/json'}};
  
    fetch(
      'https://api.opensea.io/api/v1/collections?asset_owner=0x3FB65FEEAB83bf60B0D1FfBC4217d2D97a35C8D4&offset=0&limit=3',
      // `https://api.opensea.io/api/v1/collections?asset_owner=${_account}&offset=0&limit=3`,
       options)
      .then(response => response.json())
      .then(response => {
        setData(response);
        console.log(response)})
      .catch(err => console.error(err));
  };
  return (
    <div className="App">
      <button
        onClick={connect}>
          Connect
      </button>
      {data.map(nft => {
        return(<div>
          <img src={nft.featured_image_url} width="100px" height="100px"/>
          <p>
            {nft.discord_url}
          </p>
          <p>
            {nft.banner_image_url}
          </p>
        </div>)
      })}
      <button
        onClick={getData}>
          GetData
      </button>
      
    </div>
  );
}

export default App;

The code actually works as I expected. but when opening debug console from chrome I can see this warning pasted above.

Not sure why this warning? need some help, thank you

Googled this warning msg but cannot find useful info for this warning. Is this warning a real issue or this can be ignored?

CodePudding user response:

You need to add a key to your returned element, because React need to differentiate each elements.

You just need to add the parameter key to your block like:

{data.map(nft => (
  <div key={nft.id}>
    <img src={nft.featured_image_url} width="100px" height="100px"/>
    <p>
      {nft.discord_url}
    </p>
    <p>
      {nft.banner_image_url}
    </p>
  </div>
))}

Why did I used nft.id ?

Most often, peoples use array map()'s index property as key, but it can be a bad practice depending on your goal. using:

{data.map((nft, index) => (
  <div key={index}>
    ...
))}

Works pretty fine, BUT in some cases (not that rare), when you perform edit action on your array's element, and you end up sorting them, React will be very confused.

Imagine you create an online music platform such as Spotify, and your API return you a list of your own playlist, ordered by name. The day you'll edit one playlist name, your entire playlist will have unwanted comportement because your element array's order will be modified, and the index you used as key.

So you may use map's index property as key, but be aware of what you need, it's generally better to use your element's id, uuid or other unique value as key. See more on the official website

CodePudding user response:

You must provide a unique key when you map with react.

Here is how :

 {data.map((nft, index) => {
        return(<div key={index}>

This is just an example. You can provide your own index.div key={nft} could work too if it is unique for each data.

  • Related