Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js, error about keys when map on array

Tags:

reactjs

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

like image 541
czlowiek488 Avatar asked Dec 07 '25 04:12

czlowiek488


1 Answers

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}>
like image 95
Chris Avatar answered Dec 12 '25 14:12

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!