Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  55] [ 1]  / answers: 1 / hits: 23831  / 6 Years ago, sun, april 15, 2018, 12:00:00

I am just starting with ReactJS and tried solutions of other questions similar to this but no luck so far.



Here is my working code :



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


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

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


But when I am passing Numbers Array as :



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


I am getting this error :



Warning: Encountered two children with the same key, 4. Keys should be unique so that components maintain their identity across updates.



So my Question is : What is the best way to give keys in this situation? And if I am using Number (as in above example) as Keys, what is the best solution to avoid this warning?



Thank You!


More From » reactjs

 Answers
26

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>




[#54661] Thursday, April 12, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
destiniemartinac

Total Points: 92
Total Questions: 106
Total Answers: 111

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;