1

I have an Array. I'm using map to show it in React. React throw me error about keys, I don't know why. Any ideas why is React throw this error?

{
    this.state.buttons.map((button, index) => {
       return (
       <>
         {index % 4 === 0 && (
           <div key={`break-${index}`} className="w-100" />
         )}
         <Button key={index} char={button} click={this.pushString} />
       </>
     )
})}

enter image description here

Siavash
  • 2,813
  • 4
  • 29
  • 42
czlowiek488
  • 187
  • 2
  • 17
  • 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) – Aswin Ramesh Oct 22 '18 at 13:32

2 Answers2

5

The issue here is that you passed your index to your div, which isn't the top-level component returned in your map() - your <> (React Fragment) is.

The quick-fix here would be to give it the key. However, since the short syntax doesn't support any attributes, you need to use the longer, explicit syntax to declare keys there:

<React.Fragment key={index}>
Chris
  • 57,622
  • 19
  • 111
  • 137
2
{this.state.buttons.map((button, index) => {
               return (
               <div key={index}>
                 {index % 4 === 0 && (
                   <div  className="w-100" />
                 )}
                 <Button char={button} click={this.pushString} />
               <div/>
             )
           })}

Keys need to be unique. Pass index as key

Roopak Puthenveettil
  • 1,387
  • 2
  • 13
  • 27