czlowiek488
czlowiek488

Reputation: 235

React js, error about keys when map on array

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

Upvotes: 2

Views: 3106

Answers (2)

Chris
Chris

Reputation: 59491

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}>

Upvotes: 7

Roopak Puthenveettil
Roopak Puthenveettil

Reputation: 1475

{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

Upvotes: 2

Related Questions