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!
You create your object (including its id property) and then you add it to the result array. You add the id property to the last object in your result array (since you talk about "newly created data" I am assuming it is always the last item).
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.
How we will render an Array of Objects? We will use the map function to access each object from the array. The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array.
You should add a key to each child as well as each element inside children. This way React can handle the minimal DOM change. In your code, each <TableRowItem key={item.id} data={item} columns={columnNames}/> is trying to render some children inside them without a key. Check this example.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With