1

I have a JSON string like below. The string has \n for the next line.

data:{a:"A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. Modern computers have the ability to follow generalized sets of operations, called programs. These programs enable computers to perform an extremely wide range of tasks. A "complete" computer including the hardware, the operating system (main software), and peripheral equipment required and used for "full" operation can be referred to as a computer system. This term may as well be used for a group of computers that are connected and work together, in particular, a computer network or computer cluster.\nComputers are used as control systems for a wide variety of industrial and consumer devices. This includes simple special purpose devices like microwave ovens and remote controls, factory devices such as industrial robots and computer-aided design, and also general-purpose devices like personal computers and mobile devices such as smartphones. The Internet is run on computers and it connects hundreds of millions of other computers and their users."}

I used it in React like below:

const b = data.a.split("\n");
return(
<P>
b.map((p,index)=>({p}<br key={index}/>))
</p>

I got an ES lint warning For the above code. The warning is like below.

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

How could I avoid the warning? I need a text in the paragraph tag and each line breaks in the text (\n) substitute by <br/>

Sabesan
  • 654
  • 1
  • 10
  • 17
  • Does this answer your question? [Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of \`ListView\`](https://stackoverflow.com/questions/34576332/warning-each-child-in-an-array-or-iterator-should-have-a-unique-key-prop-che) – wentjun Apr 26 '20 at 20:13
  • @wentjun It looks similar but here I got a different Issue. If I use to like the correct method which I marked then I need to remove padding and margin in CSS. Therefore I use the above method. – Sabesan Apr 27 '20 at 16:30

2 Answers2

2
b.map((p,index)=>(<p key={index}>{p}</p>))

You need the key on a wrapping element. Just use a p tag and you get the line break for free. ;)

There are reasons that using index as your key is a bad idea, though.

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
  • Yes, I had a padding issue, therefore, I try to use the method in question. Now I remove the padding and use this method. Thank you for your help. – Sabesan Apr 27 '20 at 16:26
0

You need to set key attribute to the item returned from map instead of <br> element.

Try something like this:

<P>
  { React.Children.toArray(b.map((p,index)=>({p}<br/>))) }
</p>
koorosh
  • 414
  • 4
  • 7