Home > Blockchain >  I assigned each element in my list a unique key, but am still receiving the 'Warning: Each chil
I assigned each element in my list a unique key, but am still receiving the 'Warning: Each chil

Time:10-04

I am new to React and not sure why I am receiving this error. I assigned each list element a key in my map method, but am still getting an error saying each element should be assigned a key. Here is my code:

import React, { useState, useEffect } from "react";
import "./App.css";

const namesURL = "http://api.names.com/search/names"; 

function App() {
const [names, setNames] = useState([]); 

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

  const getNames = async () => {
    const response = await fetch(namesURL); 
    const jsonData = await response.json(); 
    jsonData.sort(function(a, b) { 
      let textA = a.name
      let textB = b.name
      return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
  }); 
    console.log(jsonData); 
    setNames(jsonData); 
  };

  return (
    <div className="App">
       {names.map(name => ( 
         <ul>
          <li key={name.id}> 
            <h2>{name.name}</h2>
            <div></div>
            <img src={name.image} alt="image"></img>
            <hr></hr>
          </li>
          </ul>
          ))}  
      </div>
  );
}

export default App;

CodePudding user response:

{names.map(name => ( 
  <ul>
    <li key={name.id}> 

The key needs to be on the outermost element of the array. So if you meant to have multiple uls like your current code does, then do:

{names.map(name => ( 
  <ul key={name.id}>
    <li>

However, it may be a mistake to have multiple uls: you're doing multiple lists, each with one item. If instead you meant to do a single list with multiple items, then move the ul outside the map. That will make the li be the outermost element, and then the key can stay on the li:

<ul>
  {names.map(name => ( 
    <li key={name.id}>
  • Related