ReactJS : What is the best way to give keys in array element

Do this add a unique key as well as custom data

import React from 'react';
import ReactDOM from 'react-dom';


const Numbers = ['2', '4', '6', '8'];

const NumbersList = (props) => (
   <ul>
      {
          props.Numbers.map (
             (number, i) => <li key={i} custom={number}>{number * 2}</li>
          )
      }
    </ul>
)
ReactDOM.render(<NumbersList Numbers = {Numbers} />, document.getElementById('root') )

The key prop should be unique so I gave the returned value from the map method, custom attribute will be the array data that you want to set for all the elements.


When you don't have a definitive unique property for the items (a list of non unique primitives), you can use the index.

Note: don't use the index if the items have a unique id (and a non-primitives list should), because it's an anti-pattern.

const Numbers = ['2', '4', '4', '8'];

const NumbersList = (props) => (
  <ul>
  {
  props.Numbers.map (
    (number, index) => <li key={index}>{number * 2}</li>
  )}
  </ul>
)

ReactDOM.render(
  <NumbersList Numbers = {Numbers} />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

The reason is Each <li> tag should have a unique key. You are assigning key=4 in your <li> tag as element 4 is duplicate in your array.

After Edit

My Bad, I didn't read the full question. use uuid package to generate new id: https://www.npmjs.com/package/uuid They have documentation as well.