2

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

1

2 Answers 2

7

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}>
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

I cant do it, bootstrap cry when I do.
Nothing, but layout is broken :/
@ŁukaszKlejszta, maybe it broke because of the div's in this answer that you didn't have before?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.