Home > database >  React key error although all elements have unique identifier
React key error although all elements have unique identifier

Time:08-07

So I am getting used to React and I understand when using the map function each item needs to be assigned a unique key. I believe I am doing this correctly

    return (
     countries.map(country => {
        return <>
        <div key={country.name.common}>
            {country.name.common} <button onClick={() => setCountries([country])}>show</button>
        </div>
        </>
      })
   )

I still receive an error in the console saying:

Warning: Each child in a list should have a unique "key" prop.

at CountryList.

at div.

Where CountryList being the file the code is extracted from. I have tried adding the same key to the button element and also tried giving the button element its own unique key.

descriptive key error message

countries is a call to "https://restcountries.com/v3.1/all" api.

useEffect(() => {
    axios.get("https://restcountries.com/v3.1/all")
         .then(response => setCountries(response.data))
  }, [])
const handleFilterChange = (event) => {
    setFilter(event.target.value)
    const filtered = countries.filter(country => country.name.common.toLowerCase().includes(event.target.value))
    setCountries(filtered)
  }

console error message along with what the app looks like

CodePudding user response:

The key must be placed on the parent element that you are returning from the map function.
Since it's a fragment in this case, you can't directly assign a key to it, unless you use the actual fragment component.

// Can't assign a key
<></>
// Can assign a key
<React.Fragment key={...}></React.Fragment>

Then again, if you only have the div here, why do you need the fragment?
A shorter syntax of your code would look like this:

return (
   countries.map(country => (
      <div key={country.name.common}>
         {country.name.common}
         <button onClick={() => setCountries([country])}>show</button>
      </div>
   ))
)

CodePudding user response:

You are using <> as a perent tag and add key in child <div> tag. remove <></> as you dont need this or use Fragment insted

  return countries.map(country => (
    <div key={country.name.common}>
      {country.name.common}
      <button onClick={() => setCountries([country])}>show</button>
    </div>
  ))

or

return countries.map(country => {
  return (
    <React.Fragment key={country.name.common}>
      <div>
        {country.name.common} <button onClick={() => setCountries([country])}>show</button>
      </div>
    </React.Fragment>
  )
})
  • Related